I have this:
var one = ['12','24','36'];
var two = ['10','20','30'];
If I do:
alert(one) I have: 12,24,36. And it's ok.
I need to have the name of the array from another function, where I call it from a for like this:
var test = [one,two]
for (i = 0; i < test.length; i++) {
alert(test[i]);
}
I have "12,24,36" and then "10,20,30" in the alert, but I need the name of the array, not the content. How to do?
I want two alert with: "one" and "two", the name of Array.
Use an object to hold your arrays:
var obj = {
one: ['12','24','36'],
two: ['10','20','30']
}
for (var p in obj) {
console.log(p); // log the key
}
Alternatively you can use Object.keys(obj) to retrieve an array of the object keys.
And if you need to log the array contents:
for (var p in obj) {
console.log(obj[p]); // log the array contents
}
DEMO
Yes, I agree with elad.chen. You can try something like:
var objects = [
{name:"one",value:['12','24','36']},
{name:"two",value:['12','24','36']}
];
for(var i=0;i<objects.length;i++){
console.log(objects[i].name);
console.log(objects[i].value);
}
You can use an "Object Literal" and use the property name as the name, and the value as the array..
For example:
var arrays = {
"one": [1,2,3],
"two": [1,2,3]
}
for ( var k in arrays ) {
alert('"Array name" = ' + k)
alert('"Array value" = ' + arrays[k].toString() )
}
At some place, the name must be set. While Javascript is can add properties to objects, this can be used for a name property without changing the behaviour of the arrays.
var one = ['12', '24', '36'];
one.name = 'one';
var two = ['10', '20', '30'];
two.name = 'two';
var test = [one, two], i;
for (i in test) {
document.write(test[i].name + '<br>');
}
Related
I want to insert duplicate values into array based on length provided like this:
var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}];;
var dataTypesLength= 4;
Output should be like:
var a = [{displayName: 'bar'},{displayName: 'bar'},{displayName: 'bar'},{displayName: 'bar'}, {displayName:'google'},{displayName:'google'},{displayName:'google'},{displayName:'google'}, {displayName:'mod'}, {displayName:'mod'}, {displayName:'mod'}, {displayName:'mod'}];
I tried this:
a = a.flatMap( word => Array.from({ dataTypesLength}).fill( word ));
but I am getting typescript error saying: Argument of type '{ dataTypesLength: any; }' is not assignable to parameter of type 'ArrayLike<{}>'.
Object literal may only specify known properties, and 'dataTypesLength' does not exist in type 'ArrayLike<{}>'
Just loop the array of objects and use fill to get your result.
var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}];
var dataTypesLength= 4;
var arr=[];
function fillArray(value, len) {
return Array(len).fill(value);
}
for (var i=0; i<a.length; i++){
var b = fillArray(a[i],dataTypesLength);
arr.push(...b);
}
console.log(arr);
You can use this (single line solution):
a.reduce((acc,x)=>{ acc.push(...new Array(dataTypesLength).fill(x)); return acc;}, [])
Explaination :
Reducing the input array starting from empty array []
For every element creating a new array with length dataTypesLength and filling all the new array with the current element new Array(dataTypesLength).fill(x)
Spread the new created array and push it into accumulator array acc.push(...new Array(dataTypesLength).fill(x))
Return the accumulator array
You can use map with Object.assign so that each object will have independent reference
var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}];
var dataTypesLength= 4;
a= a.map(obj => { return Array(dataTypesLength).fill(null).map( e => Object.assign({}, obj)) }).flat();
console.log(a)
you can try reduce
var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}];;
var dataTypesLength= 4;
a = a.reduce(
(f,obj ) => {
var dup = new Array(dataTypesLength);
f.push(...dup.fill(obj));
return f;
}, [] )
I know it's simple, but I don't get it.
I have this code:
// My object
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);
If I do this I'll get a simple array:
["Title", "Ramones"]
I need to create the following:
[{"01":"Title", "02": "Ramones"}]
How can I use push() to add the object into the nietos array?
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
Create an array of object like this:
var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;
First you create the object inside of the push method and then return the newly created array.
can be done like this too.
// our object array
let data_array = [];
// our object
let my_object = {};
// load data into object
my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
// push the object to Array
data_array.push(my_object);
Using destructuring assignment (ES6)
const nieto = {label: 'title', value: 'ramones' }
const modifiedObj = {01: nieto.label, 02: nieto.value}
let array = [
{03: 'asd', 04: 'asd'},
{05: 'asd', 06: 'asd'}
]
// push the modified object to the first index of the array
array = [modifiedObj, ...array]
console.log(array)
If you'd like to push the modified object to the last index of the array just change the destructured array ...array to the front.
array = [...array, modifiedObj]
Well, ["Title", "Ramones"] is an array of strings. But [{"01":"Title", "02", "Ramones"}] is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue; in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[], so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({}), or myArray.push({""}).
This will push an empty object into myArray which will have an index number 0, so your exact object is now myArray[0]
Then push property and value into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";
I'm not really sure, but you can try some like this:
var pack = function( arr ) {
var length = arr.length,
result = {},
i;
for ( i = 0; i < length; i++ ) {
result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
}
return result;
};
pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}
The below solution is more straight-forward. All you have to do is define one simple function that can "CREATE" the object from the two given items. Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.
var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
for (var j=0; j<arr1.length; j++) {
resultArray[j] = new makeArray(arr1[j], arr2[j]);
}
function makeArray(first,second) {
this.first = first;
this.second = second;
}
This solution can be used when you have more than 2 properties in any object.
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
let xyz = Object.entries(nieto)
xyz.forEach((i,j)=>{
i[0] = `${(j+1).toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}`
})
nietos.push(Object.fromEntries(xyz))
I have a function that takes in an Array, iterates over it finding all Objects and displays them to the UI.
In rare cases, I have to supply an Object (result from a WS as application/JSON) which is not an Array by default and hence my function fails to iterate over it and display on the UI.
In normal cases my Array looks like this:
[
{ "name" : "foo"},
{ "name" : "bar"},
{ "name" : "baz"}
]
and this works like it is supposed to. However, sometimes the data I get could be this:
{ "name" : "I am not in a List"}
and my function that takes in an array looks like this:
function loadJSONIntoUI(data) {
for (var aMsg = 0; aMsg < data.length(); aMsg++) {
// Do something with each `index` in the List
}
}
Is there a way I can detect that the single object which is not an array is an odd one and probably put it into a List on the fly and pass it to a function?
So far I have tried to use typeof and also tried to create a new Array on the fly and push my object into it but it prints out a 1 when I do that.
A one liner using Array.prototype.flat:
[couldBeArray].flat()
Examples:
const anObj = {name: "Hi"};
const anArr = [{name: "Hi"}];
const wrapped1 = [anObj].flat()
const wrapped2 = [anArr].flat()
console.log(wrapped1); // wrapped1 is [{name: "Hi"}]
console.log(wrapped2); // wrapped2 is [{name: "Hi"}]
You can simply use Array.concat() to auto-wrap an object into an array:
const obj = {name: "foo"};
const arr = [{name: "bar"}];
const result1 = [].concat(obj); // result1 is [{name: "foo"}]
const result2 = [].concat(arr); // result2 is [{name: "bar"}]
console.log(result1)
console.log(result2)
you can transform it in an array if is not and let iterate one time:
function loadJSONIntoUI(data) {
if(!(data instanceof Array)){
data = [data];
}
for (var aMsg = 0; aMsg < data.length; aMsg++) {
// Do something with each `index` in the List
}
}
Also, length doesn't need to be called like a method.
Let me know if it works
Cheers
Array.isArray can be used to achieve what you need:
function loadJSONIntoUI(data) {
if(!Array.isArray(data)) {
data = [data];
}
for (var aMsg = 0; aMsg < data.length(); aMsg++) {
// Do something with each `index` in the List
}
}
You need to check for an array and fix an error - should be just data.length, no brackets. See code below, check demo - https://fiddle.jshell.net/ermakovnikolay/fgedaubm/
function loadJSONIntoUI(data) {
var data = Array.isArray(data) ? data : [ data ];
for (var aMsg = 0; aMsg < data.length; aMsg++) {
// Do something with each `index` in the List
console.log(data[aMsg]);
}
}
You can use Array.of(). So in your case Array.of(data) returns [{ "name" : "I am not in a List"}]
Where exactly is wrong here? I get a "Cannot read property 'push' of undefined" error, and I believe that's because the array can't be set to multidimensional by simply declaring it in the loop.
var single = [];
for (var i = 0; i < all.length; i++) {
name = all[i].name;
single[name].push(all[i]);
}
What I'm trying to achieve is this structure:
Array (
([name1] => [node1],[node2],[node3]),
([name2] => [node1],[node2],[node3],[node4],[node5],[node6]),
([name2] => [node1],[node2])
etc...
)
I've tried searching here on SO, but so far only got two options:
Option 1: Shorthand in declaring the variable, aka [[]], which doesn't work.
var single = [[]];
Option 2: link Add another loop to work out the array before filling it.
var matrix = []
cols = 3;
//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
matrix[i] = [];
}
I'd rather find a shorter solution, also because my array elements MUST have the key, while on the solution above they are numbered.
EDIT: since keys in JS array are not an option, would an object do the trick in this case? something like:
var obj = {
key1: value1,
key2: value2
};
obj.key3 = "value3";
You can use object or Map (ES6) data structure to achieve this, e.g.:
var single = {};
for (var i = 0; i < all.length; i++) {
name = all[i].name;
if (!single[name]) {
single[name] = [];
}
single[name].push(all[i]);
}
the result (single object) looks like:
{
name1: [node1, node2, node3],
name2: [node1, node2, node3, node4, node5, node6],
name2: [node1, node2]
}
Javascript uses objects and arrays. There is no multidimensional-array.
The structure you want would look like this in javascript:
{
name1: [a,b,c],
name2: [d,e,f]
}
In fact in JS, you can just define a variable with such a object like this (object literal):
var myObject = {
name1: [a,b,c],
name2: [d,e,f]
}
You do not need to iterate to construct an object in JS, object-literals are easy to understand and fast.
If for some reason you need to map some data to this new format you want, I personally would use methods such as the Array.prototype.reduce.
myMap = all.reduce(function (result, item) {
result[item.name] = (result[item.name] || []).push(item);
return result;
},{});
I have following Jsonstring
var j = { "name": "John" };
alert(j.length);
it alerts : undefined, How can i find the length of json Array object??
Thanks
Lets start with the json string:
var jsonString = '{"name":"John"}';
you can easily determine its length:
alert("The string has "+jsonString.length+" characters"); // will alert 15
Then parse it to an object:
var jsonObject = JSON.parse(jsonString);
A JavaScript Object is not an Array and has no length. If you want to know how many properties it has, you will need to count them:
var propertyNames = Object.keys(jsonObject);
alert("There are "+propertyNames.length+" properties in the object"); // will alert 1
If Object.keys, the function to get an Array with the (own) property names from an Object, is not available in your environment (older browsers etc.), you will need to count manually:
var props = 0;
for (var key in jsonObject) {
// if (j.hasOwnProperty(k))
/* is only needed when your object would inherit other enumerable
properties from a prototype object */
props++;
}
alert("Iterated over "+props+" properties"); // will alert 1
Another way of doing this is to use the later JSON.stringify method which will give you an object (a string) on which you can use the length property:
var x = JSON.stringify({ "name" : "John" });
alert(x.length);
Working Example
function getObjectSize(o) {
var c = 0;
for (var k in o)
if (o.hasOwnProperty(k)) ++c;
return c;
}
var j = { "name": "John" };
alert(getObjectSize(j)); // 1
There is no json Array object in javascrit. j is just an object in javascript.
If you means the number of properties the object has(exclude the prototype's), you could count it by the below way:
var length = 0;
for (var k in j) {
if (j.hasOwnProperty(k)) {
length++;
}
}
alert(length);
An alternate in Jquery:
var myObject = {"jsonObj" : [
{
"content" : [
{"name" : "John"},
]
}
]
}
$.each(myObject.jsonObj, function() {
alert(this.content.length);
});
DEMO