简体   繁体   中英

How to access array stored in Json object?

I've json response like this, I want to get all project names from this.

I have done as usual as iterate through arrays but here "d" is not an array. 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() :

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)

You can use jsonObject.d.results to get the array from response and use forEach() to iterate array

 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()

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

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.

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