访问 JSON 数组中的对象 (JavaScript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14217790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:03:29  来源:igfitidea点击:

Accessing Objects in JSON Array (JavaScript)

javascriptarraysjsonobject

提问by maze

Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?

可能重复:
我有一个嵌套的数据结构/JSON,如何访问特定值?

I have a service that returns nested Objects in a JSON Array. How can I loop through the objects and print the desired data?

我有一个服务,它返回 JSON 数组中的嵌套对象。如何遍历对象并打印所需的数据?

This is my result:

这是我的结果:

[
{
    "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"
    }
}
]

This is what I want to print for each item (item1, item2, item3, ...):

这是我要为每个项目(item1、item2、item3、...)打印的内容:

Item Name: item1
Source: 5599ffac-4b99-47c7-9370-a25e7e465429
Target: 5599ffac-4b99-47c7-9370-a25e7effffff

So far I tried:

到目前为止,我尝试过:

for (var i = 0, length = data.length; i < length; i++) {
for (obj in data[i]) {
    console.log(obj);

}
}

This only returns "item1", "item2" etc. But I don't know how access sourceUuid etc. from there

这仅返回“item1”、“item2”等。但我不知道如何从那里访问 sourceUuid 等

回答by Bergi

You can loop the array with a for loopand the object properties with for-in loops.

您可以使用for 循环循环数组,使用for-in 循环循环对象属性。

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);
    }

回答by Naftali aka Neal

Use a loop

使用循环

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]);
        }
   }
}

Demo: http://jsfiddle.net/maniator/pngmL/

演示:http: //jsfiddle.net/maniator/pngmL/