"obj" : {
"a" : [
{ "name" : "value" },
{ "name" : "value" },
{ "name" : "value }
],
"b" : [
{ "name" : "value" },
{ "name" : "value" },
{ "name" : "value" }
]
};
I have my json structured similarly to this in that "a" and "b" are objects that contain arrays which also contain objects. I'm not very good with iteration/loops. I mainly would like to get the value of "name". any help? THANKS IN ADVANCE!
var foo = JSON.parse(json);
for(var i in foo){
for(var y = 0; y < foo[i].length; y++)
alert(foo[i][y].name);
}
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse
You can use forEach
:
Object.keys( json.obj ).forEach(function ( key ) {
json.obj[ key ].forEach(function ( obj ) {
// retrieve obj.name here
});
});
Live demo: http://jsfiddle.net/4Mrkp/
Using underscore.js ->
var obj = {
"a" : [
{ "name" : "value" },
{ "name" : "value" },
{ "name" : "value" }
],
"b" : [
{ "name" : "value" },
{ "name" : "value" },
{ "name" : "value" }
]
};
var names = _.chain(obj).values().flatten().pluck('name').value();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.