This question already has answers here:
How to get property value in js object when key is unknown
(3 answers)
Closed 3 years ago.
Using the following generated array example structure, how can I loop through and extract the property names and their associated values from each object?
[{"bg_2":"0.50"},{"bg_7":"0.10"},{"bg_12":"0.20"}]
The number of objects may change, and the property names will not be consistent.
You can use Object.keys()[0] to get the key, then use the key to get the value.
JSFiddle
var myData = [{"bg_2":"0.50"},{"bg_7":"0.10"},{"bg_12":"0.20"}];
for (var i = 0; i < myData.length; i++) {
var myObject = myData[i];
var firstKey = Object.keys(myObject)[0];
var value = myObject[firstKey];
console.log(firstKey + ": " + value);
}
See also: ECMAScript® Language Specification: 15.2.3.14 Object.keys ( O )
Expanding on #AR7's answer, in the case that there may be multiple properties in each of the objects you can cache the object returned by Object.keys() and loop through each property within the array loop.
Using the method below, you can handle any number of properties within the object.
I realize this may not be any more useful in this specific situation than the aforementioned answer, but hopefully it will be useful to future viewers.
JSFiddle
var a = [
{ "bg_2":"0.50", "bg_7":"0.10", "bg_12":"0.20"},
{ "bg_2":"0.50", "bg_7":"0.10"},
{ "bg_2":"0.50"}
];
a.forEach(function(o){
console.log(o);
var k = Object.keys(o);
for(var i in k)
console.log(k[i], ':', o[k[i]]);
});
Related
This question already has answers here:
Does JavaScript guarantee object property order?
(13 answers)
Closed 4 years ago.
Within the example script I have generated two arrays I would like to combine to a single row:
var testHeaders = ["aLabel", "bLabel", "cLabel","dLabel","eLabel"];
and
var testValue = ["aValue","bValue", "cValue","dValue","eValue"];
What I am trying to achieve is a string like { aLabel = aValue, bLabel = bValue, ... } that can be used to upload into BigQuery (the data upload job works).
I found a piece of code that almost does this, but somehow it changes the order of the elements within the two arrays.
var code = testValue.reduce(function(obj, value, index) {
obj[testHeaders[index]] = value;
return obj
}, {})
However, the result does mix up the order of the arrays as seen below. I am not capable of figuring out why the order changes. As far as I know, reduce() should work its way from left to right in an array.
The returned object is:
{
aLabel = aValue,
dLabel = dValue,
bLabel = bValue,
eLabel = eValue,
cLabel = cValue
}
You can use map and join:
var testHeaders = ["aLabel", "bLabel", "cLabel","dLabel","eLabel"];
var testValue = ["aValue","bValue", "cValue","dValue","eValue"];
var res = '{' + testHeaders.map((label, i) => `${label}=${testValue[i]}`).join(',') + '}';
console.log(res);
As vlaz pointed out, you are creating neither a string or a new array, but an object. And just like maps, objects do not have a set order of keys in JavaScript. hence, there is quite a chance of getting another order in the object than in both arrays.
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Modifying a copy of a JavaScript object is causing the original object to change
(13 answers)
Closed 25 days ago.
In the code below you see that it recognises arrayi as array - i.
Is this system built into js? I was experementing and it didn't function when I wrote array(i) instead of arrayi. The question then extends beyond all to ask if you could do iarray, ariray, arrayii or array(i*i) (just want to figure out the syntax of how this works).
var array = []
var arrayAmount = prompt("Select number of array")
for (var i = 0; i < arrayAmount; i++) {
var arrayi = array
arrayi.push([prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-elemet 2"], ])
console.log(arrayi)
}
console.log(array1)
Edit: I checked if the code would work if the for loop declares its own arrays instead of copying another array. Turns out it did not work and declared arrayi as arrayi instead of array1 or array2
You're confusing several JS concepts. I'll make some assumptions to explain some things, but feel free to correct me and I'll adjust my answer.
I believe you meant to assign a value at a particular index in the array, but what you ended up doing is creating a variable arrayi that is a reference to array:
var array = [];
array[1] = "foo";
console.log(array); // [undefined, "foo"]
What you did instead was create a reference, which means two different variable names will evaluate to the same object/array:
var array = [];
var reference_to_array = array;
reference_to_array.push("foo");
console.log(array); // ["foo"]
console.log(reference_to_array); // ["foo"]
Your original question includes: "and it didn't function when I wrote array(i) instead of arrayi".
To which the answer is: array(i) should be changed to array[i] when working with arrays.
Instead of fixing your original issue, you ended up creating new variables.
To fix your original code:
var array = [];
// Added parsing to an integer
var arrayAmount = parseInt(prompt("How many items do you want to add to the array?"));
for (var i = 0; i < arrayAmount; i++) {
// Method 1: directly access the index
//array[i] = [ prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-element 2"] ];
// Method 2 (Recommended): push a new element onto the end of the array
array.push([ prompt("Select name for array " + (i + 1)), ["sub-element 1", "sub-element 2"] ]);
// Log this element
console.log(array[i]);
}
This question already has answers here:
How do I iterate over a JSON structure? [duplicate]
(13 answers)
Closed 8 years ago.
I am not a javascript expert, so I am sure what I am trying to do is pretty straight forward, but, here it is:
I have an array that comes down from a database, it looks like this:
[{"name":"aName","lastName":"aLastname"},{"name":"bName","lastName":"bLastname"}]
I want to iterate through all dictionaries found in the array and access the aName, aLastname etc... so all possible values found in each dictionary, a dictionary at the time.
I tried using eval(), I tried to use JSON.parse, but JSON.parse I think was complaining because I think the object was already coming down as JSON.
How can I do that in javascript?
Thanks
So then I tried to do what was suggested by the "duplicate" answer comment... I did this:
for(var i=0; i<array.length; i++) {
var obj = array[i];
for(var key in obj) {
var value = obj[key];
console.log(key+" = "+value);
}
}
Problem is that the log is out of order. I get this:
name = aName
name = bName
lastName = aLastName
lastName = bLastName
I want to be sure I iterate through the properties and values in order one dictionary at the time.
What am missing here?
var test = [{"name":"aName","lastName":"aLastname"},{"name":"bName","lastName":"bLastname"}];
for (var i = 0; i < test.length; ++i) {
alert(test[i].name + ", " + test[i].lastName);
}
http://jsfiddle.net/1odgpfg4/1/
You may want to try this.
var arr = [{"name":"aName","lastName":"aLastname"},{"name":"bName","lastName":"bLastname"}];
arr.forEach(function(d){
console.log(d.name, d.lastName);
});
This question already has answers here:
How do I enumerate the properties of a JavaScript object? [duplicate]
(14 answers)
Closed 8 years ago.
In Javascript, I'd like to have an object with three properties, "zone1", "zone2", "zone3", each of which store an array of place names. I would like to search for a match by iterating through the arrays to find a place name.
The following questions almost gets me there, but don't work for me because I am not using jQuery, and I want the value, not the key:
Performing a foreach over an associative array of associative arrays
Getting a list of associative array keys
My code looks like this:
var zoneArray = {};
zoneArray["zone1"] = ["placeA", "placeB"];
zoneArray["zone2"] = ["placeC", "placeD"];
function getZone(place, zoneArray) {
var zone;
for (var key in zoneArray) {
for(i = 0; i<key.length; i++) {
if(key[i] == place) {
zone = key;
return zone;
}
}
}
}
getZone("placeC", climateZoneArray);
Apparently however, "key[i]" is referring to letters of the zone names, like, "z" "o" "n" "e"
Could anybody please help me understand or best handle this situation in Javascript?
Use zoneArray[key] to access the array.
for (var key in zoneArray) {
var arr = zoneArray[key]
for(i = 0; i<arr.length; i++) {
if(arr[i] == place) {
zone = key;
return zone;
}
}
}
Using for ... in to iterate over an object's properties can lead to some pretty surprising results, especially if you're working in an environment where Object.prototype has been extended. This is because for ... in will iterate over an objects enumerable properties and the enumerable properties contained in that objects prototype chain. If this isn't what you want but you are going to use for ... in anyways, it's recommended to have a conditional statement at the top of the loop that checks that the property belongs to the object which is being iterated over. (if (!foo.hasOwnProperty(x)) continue;). Luckily, there is Object.keys(). You can use Object.keys() to get an array of an objects own enumerable properties, if you do this you can skip hasOwnProperty ugliness. Instead of iterating over the object you can iterate over an array of it's keys.
var collection = {
zone1: ['placeA', 'placeB'],
zone2: ['placeC', 'placeD']
};
function getZone(needle, collection) {
var zones = Object.keys(collection),
found;
for (var i = 0, l = zones.length; i < l; i++) {
found = collection[zones[i]].filter(function(place) {
return needle == place;
});
if (found.length > 0) {
return zones[i];
}
}
};
console.log(getZone('placeC', collection));
This is also here on jsfiddle.net
One last thing, be very careful when creating variables, in the inner for loop you created the variable i without using the var keyword. This resulted in i being bound to the global context, something you really want to avoid.
This question already has answers here:
Elements order in a "for (… in …)" loop
(10 answers)
Closed 8 years ago.
i need to get real order of simple javascript abject, but i get incorrect answer from this code:
var Obj={"x":"z", "2":"a", "1":"b"};
for(i in Obj)
document.write(Obj[i]+"<br>");
I expect to see z, a, b as answer, but i get b, a, z
See the code in action:
http://jsfiddle.net/gpP7m/
There's no guaranteed order in object keys iteration.
A for...in loop iterates over the properties of an object in an
arbitrary order
If you need one, use an array of key/value elements :
var obj=[
{key:"x", value:"z"},
{key:"2", value:"a"}
];
for (var i=0; i<obj.length; i++) document.write(obj[i].value+'<br>');
On a modern browser (not IE8), you can do :
document.write(obj.map(function(kv){ return kv.value }).join('<br>'));
(which doesn't do exactly the same but probably does what you want)
Check for below sample too
var data1 = {"x":"z", "2":"a", "1":"b"};
var arr = [];
var i=0;
$.each(data1,function(index,value) {
arr[i++] = value;
});
var len = arr.length-1;
while( len>=0 ) {
if( arr[len] !== undefined ) {
alert(arr[len]);
}
len--;
}
and referece link is Reverse object in jQuery.each
And fiddle update http://jsfiddle.net/gpP7m/3/