可能重复:
I have a nested data structure / JSON, how can I access a specific value?
我有一个服务,它返回JSON数组中的嵌套对象。如何遍历对象并打印所需数据?
这是我的结果:
[
{
"item1": {
"sourceUuid": "5599ffac-4b99-47c7-9370-a25e7e465429",
"targetUuid": "5599ffac-4b99-47c7-9370-a25e7effffff"
}
},
{
"item2": {
"sourceUuid": "bf63fe50-8b2b-488d-b565-009fcaebdb45",
"targetUuid": "-1"
}
},
{
"item3": {
"sourceUuid": "0005fd96-f654-4781-8602-09fedc0cdd35",
"targetUuid": "0005fd96-f654-4781-8602-09fedc0cdd35"
}
}
]
这就是我要为每个项目打印的内容(item1,item2,item3,...):
Item Name: item1
Source: 5599ffac-4b99-47c7-9370-a25e7e465429
Target: 5599ffac-4b99-47c7-9370-a25e7effffff
到目前为止,我试过了:
for (var i = 0, length = data.length; i < length; i++) {
for (obj in data[i]) {
console.log(obj);
}
}
这只返回“item1”,“item2”等。但我不知道如何从那里访问sourceUuid等
答案 0 :(得分:32)
您可以使用for loop循环数组,使用for-in loops循环对象属性。
for (var i=0; i<result.length; i++)
for (var name in result[i]) {
console.log("Item name: "+name);
console.log("Source: "+result[i][name].sourceUuid);
console.log("Target: "+result[i][name].targetUuid);
}
答案 1 :(得分:5)
使用循环
for(var i = 0; i < obj.length; ++i){
//do something with obj[i]
for(var ind in obj[i]) {
console.log(ind);
for(var vals in obj[i][ind]){
console.log(vals, obj[i][ind][vals]);
}
}
}