[英]How to access array stored in Json object?
我有這樣的json響應,我想從中獲取所有項目名稱。
我像平常一樣遍歷數組,但這里的“ d”不是數組。 如何取得結果:
{
"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 names = myData.d.results.map(function(item){
return item.ProjectName;
});
這將導致如下數組:
["Payroll", "Permanant"]
(假設myData
是您問題中的對象)
您可以使用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>') })
如果要以數組形式獲取它,則可以使用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.