简体   繁体   English

如何访问存储在Json对象中的数组?

[英]How to access array stored in Json object?

I've json response like this, I want to get all project names from this. 我有这样的json响应,我想从中获取所有项目名称。

I have done as usual as iterate through arrays but here "d" is not an array. 我像平常一样遍历数组,但这里的“ d”不是数组。 How can I do to get result: 如何取得结果:

{
    "d": {
    "results": [
        {
            "ProjectId": "696fcc7c-f355-e511-93f0-00155d008500",
            "ProjectName": "Payroll",
            "EnterpriseProjectTypeDescription": null,
            "EnterpriseProjectTypeId": null,
            "EnterpriseProjectTypeIsDefault": null
        },
        {
            "ProjectId": "696fcc7c-f355-e511-93f0-00155d008505",
            "ProjectName": "Permanant",
            "EnterpriseProjectTypeDescription": null,
            "EnterpriseProjectTypeId": null,
            "EnterpriseProjectTypeIsDefault": null
        }
    ]
    }
}

Use Array.prototype.map() : 使用Array.prototype.map()

var names = myData.d.results.map(function(item){
    return item.ProjectName;
});

This will result in an array like: 这将导致如下数组:

["Payroll", "Permanant"]

(Assuming myData is the object in your question) (假设myData是您问题中的对象)

You can use jsonObject.d.results to get the array from response and use forEach() to iterate array 您可以使用jsonObject.d.results从响应中获取数组,并使用forEach()迭代数组

 var res = { "d": { "results": [{ "ProjectId": "696fcc7c-f355-e511-93f0-00155d008500", "ProjectName": "Payroll", "EnterpriseProjectTypeDescription": null, "EnterpriseProjectTypeId": null, "EnterpriseProjectTypeIsDefault": null }, { "ProjectId": "696fcc7c-f355-e511-93f0-00155d008505", "ProjectName": "Permanant", "EnterpriseProjectTypeDescription": null, "EnterpriseProjectTypeId": null, "EnterpriseProjectTypeIsDefault": null } ] } }; res.d.results.forEach(function(v) { document.write(v.ProjectName + '<br>') }) 

If you want to get it as an array then you can use map() 如果要以数组形式获取它,则可以使用map()

 var res = { "d": { "results": [{ "ProjectId": "696fcc7c-f355-e511-93f0-00155d008500", "ProjectName": "Payroll", "EnterpriseProjectTypeDescription": null, "EnterpriseProjectTypeId": null, "EnterpriseProjectTypeIsDefault": null }, { "ProjectId": "696fcc7c-f355-e511-93f0-00155d008505", "ProjectName": "Permanant", "EnterpriseProjectTypeDescription": null, "EnterpriseProjectTypeId": null, "EnterpriseProjectTypeIsDefault": null }] } }; var result = res.d.results.map(function(v) { return v.ProjectName; }) document.write(JSON.stringify(result)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM