访问对象的数组JSON(JavaScript的) [英] Accessing Objects in JSON Array (JavaScript)

查看:140
本文介绍了访问对象的数组JSON(JavaScript的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-i-access-a-specific-value\">I有一个嵌套的数据结构/ JSON,我怎么可以访问特定的值?

我有一个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?

这是我的结果:

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

这是我想打印每个项目的内容(项目1,项目2,项目3,...):

This is what I want to print for each item (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);

}
}

这仅返回ITEM1,ITEM2等,但我不知道如何访问sourceUuid等在那里。

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

推荐答案

您可以循环使用的 for循环并与为对象的属性-in循环的。

You can loop the array with a for loop and the object properties with 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);
    }

这篇关于访问对象的数组JSON(JavaScript的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆