I have some json-code which has multiple objects in it, as such:
[
{
"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
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.
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
Could you please let me know how to address? I should not get 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!
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.