[英]How to loop through json with multiple objects
I have some json-code which has multiple objects in it, as such: 我有一些带有多个对象的json代码,例如:
[
{
"MNGR_NAME": "Mark",
"MGR_ID": "M44",
"EMP_ID": "1849"
},
{
"PROJ_ID": "88421",
"PROJ_NAME": "ABC",
"PROJ_ALLOC_NO": "49"
}
]
And my JSON loop snippet is 我的JSON循环代码段是
function ServiceSucceeded(result)
{
for(var x=0; x<result.length; x++)
{
alert(result[i].MNGR_NAME);
alert(result[i].MGR_ID);
alert(result[i].EMP_ID);
alert(result[i].PROJ_ID);
alert(result[i].PROJ_NAME);
alert(result[i].PROJ_ALLOC_NO);
}
}
When I implement it displays alerts that say undefined
since result[0]
keys != result[1]
keys. 当我实现时,它会显示由于result[0]
键!= result[1]
键result[1]
undefined
警报。
Eg: result[0].MNGR_NAME
(1st Array) gives you "Mark"
but result[1].MNGR_NAME
(2nd Array) is not at all in the array and hence gives you undefined
例如: result[0].MNGR_NAME
(第一个数组)为您提供"Mark"
但result[1].MNGR_NAME
(第二个数组)根本不在数组中,因此给您undefined
Could you please let me know how to address? 您能否让我知道如何处理? I should not get undefined
. 我不应该变得undefined
。
I would use 我会用
for(index in result) {
var obj = result[index];
for(objectIndex in obj) {
if(objectIndex != "PROJ_ALLOC_NO") {
// Only alert if the key of the object is not PROJ_ALLOC_NO
alert(objectIndex + ": " + obj[objectIndex]);
}
}
}
This loops over the array, then over the object and displays every key and value of the objects! 这将遍历数组,然后遍历对象,并显示对象的每个键和值!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.