我这样的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
}
]
}
}
答案 0 :(得分:3)
var names = myData.d.results.map(function(item){
return item.ProjectName;
});
这将产生如下数组:
["Payroll", "Permanant"]
(假设myData
是你问题中的对象)
答案 1 :(得分:1)
您可以使用 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>')
})
&#13;
如果您想将其作为数组使用,那么您可以使用 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));
&#13;