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);
});
Related
This question already has answers here:
Sorting object property by values
(44 answers)
Closed 7 years ago.
I have a JSON file (myfile.json) that looks like this:
{"3":["c","d"], "3.5":["j","k"], "1.5":["a","b"], "2.5":["x","y"] }
What I want to do open the file and sort it using d3.js file opening.
d3.json('myfile.json',function(err,datafull){
for (var myval in datafull) {
console.log(myval);
}
});
Now if I do that, the console.log will print they key in unsorted manner.
How can I sort the file?
This is different question, because it involves file parsing.
To sort object keys you can use Object.keys() method which gives an array of the given objects keys then you can use the array sort() method.
d3.json('myfile.json',function(err,data){
keys = Object.keys(data),
i, len = keys.length;
keys.sort(function(a, b) {
return a - b;
});
for (i = 0; i < len; i++)
{
var a = keys[i];
console.log(a + ':' + data[a]);
}
}
See http://jsfiddle.net/sjmcpherso/mvrWb/234/
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]]);
});
This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 9 years ago.
Hi i've been struggling a bit and i cant seem to find why the methods i found dont work, could be "fixture-0"
First Object array
personformdata[i]: "{"isInvalid":false,"agentRole":"role"}"
Second
address_ids[i] : "[{"address_id": "fixture-0" }]"
preferable out come, something like this.
"{"isInvalid":false,"agentRole":"role", "address_id": "fixture-0"}"
you can do it like:
var mergedObj={};
for(var key in personformdata[i])
mergedObj[key]=personformdata[i][key];
for(var key in address_ids[i])
mergedObj[key]=address_ids[i][key];
or if you use jQuery:
var mergedObj={};
$.extend(mergedObj, personformdata[i], address_ids[i]);
I myself usually use vanilla JavaScript and prefer not using jQuery.
you can use :
var object = $.extend({}, object1, object2);
for xample you can visit this url.
http://api.jquery.com/jQuery.extend/
If you want to create a new array with merged objects, just do this with a for loop:
var newData = { };
for (var i = 0; i < personformdata.length; i++)
{
newData[i] = {
isInvalid : personformdata[i].isInvalid,
agentRole : personformdata[i].agentRole,
address_id : address_ids[i].address_id
};
}
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/
This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
I want to know what is the fastest function that can be used to convert a json object into a java script array here an example
var j = '[{"var1":"val1", "var2":"val2"}]';
var arr ===> [var1] = "val1"
The bottom line is to avoid for loops as much as possible
Most modern browsers will support the native JSON.parse function.
var arr = JSON.parse('[{"var1":"val1", "var2":"val2"}]');
console.log(arr);
//Just to be clear for OP
console.log(Array.isArray(arr)); //true
I want the output to be Arr[var1] = "val1"] not [Object]
That means you want to object at index 0 in the array.
var obj = JSON.parse('[{"var1":"val1", "var2":"val2"}]')[0];
console.log(obj['var1']); //val1
If you only want the values:
var values = JSON.parse('[{"var1":"val1", "var2":"val2"}]').reduce(function (values, obj) {
for (var k in obj) values.push(obj[k]);
return values;
}, []);
console.log(values); //["val1", "val2"]
If I understand you correctly, you can use JSON.parse.
var json = '[{"var1": "val1", "var2": "val2"}]';
var arr = JSON.parse(json);
I usually use jQuery, though that might no longer be preferred.
var j = '[{"var1":"val1", "var2":"val2"}]';
var arr = jQuery.parseJSON( j );
This should work well in some older browsers if you need that kind of thing of course.