[英]How to loop through json with multiple objects
我有一些帶有多個對象的json代碼,例如:
[
{
"MNGR_NAME": "Mark",
"MGR_ID": "M44",
"EMP_ID": "1849"
},
{
"PROJ_ID": "88421",
"PROJ_NAME": "ABC",
"PROJ_ALLOC_NO": "49"
}
]
我的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);
}
}
當我實現時,它會顯示由於result[0]
鍵!= result[1]
鍵result[1]
undefined
警報。
例如: result[0].MNGR_NAME
(第一個數組)為您提供"Mark"
但result[1].MNGR_NAME
(第二個數組)根本不在數組中,因此給您undefined
您能否讓我知道如何處理? 我不應該變得undefined
。
我會用
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]);
}
}
}
這將遍歷數組,然后遍歷對象,並顯示對象的每個鍵和值!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.