我試圖訪問嵌套在數組中的對象。我開始與此JSON對象(它是從一個XML數據庫輸出導出):使用Javascript和下劃線嵌套對象和數組循環
{"report":
{"date":"15 Apr 2016",
"metrics":
{"metric":
[
{"name":"Bank Angle",
"display_parent_group":"Bankfull",
"display_child_group":"SiteShape",
"tolerance":"0.05",
"visits":
{"visit":
[
{"visit_id":"3047","value": "0.47"},
{"visit_id":"2164","value": "0.55"},
{"visit_id":"1568","value": "0.72"},
{"visit_id":"3431","value": "0.12"},
{"visit_id":"2428","value": "0.44"},
{"visit_id":"1567","value": "0.49"}
]}},
{"name":"Bank Angle SD",
"display_parent_group":"Bankfull",
"display_child_group":"SiteShape",
"tolerance":"0.05",
"visits":
{"visit":
[
{"visit_id":"3047","value": "0.12"},
{"visit_id":"2164","value": "0.05"},
{"visit_id":"1568","value": "0.21"},
{"visit_id":"3431","value": "0.68"},
{"visit_id":"2428","value": "0.22"},
{"visit_id":"1567","value": "0.13"}
]}},
{"name":"Bankfull Area",
"display_parent_group":"Bankfull",
"display_child_group":"SiteSize","tolerance":"0.05",
"visits":
{"visit":
[
{"visit_id":"3047","value": "202"},
{"visit_id":"2164","value": "193"},
{"visit_id":"1568","value": "115"},
{"visit_id":"3431","value": "258"},
{"visit_id":"2428","value": "89"},
{"visit_id":"1567","value": "206"}
]}}
]
}
}
}
我然後用下劃線來提取metric
對象的子集:
var table_metric = JSONData.report.metrics.metric;
var target_metrics = _.where(table_metric, {
display_parent_group : 'Bankfull', display_child_group: 'SiteShape'
});
這導致陣列具有兩個嵌套對象。我遇到問題的地方是訪問嵌套在visits.visit
中的對象數組。如果,例如,我想建立與關鍵visit_id
相關值的數組,我嘗試:
function buildVisitIDArray(target_metrics) {
var attrList = [];
for(var i=0; i<target_metrics.length; i++) {
var visit_records = target_metrics[i].visits[1];
console.log(visit_records);
for(visit_record in visit_records) {
attrList.push(_.pluck(visit_record, "visit_id"));
}
}
return attrList
}
我只是得到的結果將是不確定的數組。我花了幾個小時嘗試變化的語法來獲得嵌套的「訪問」對象,但我似乎無法弄清楚。
任何幫助是非常讚賞這個新手!
謝謝André。現在我得到一個正確長度的數組(5),但所有的項目都是'未定義的'。我仍然沒有做正確的事情。 – jesselangdon
@ tinyplanet00我的錯誤。我沒有看到函數的返回。修復。在您的for(visit_records中的visit_record)中,visit_record是一個鍵,而不是一個值。所以,你必須訪問使用visit_records [visit_record]。現在它返回一堆ID :)(代碼在我的解決方案中編輯) –
啊,是的,這個工程很漂亮。再次感謝! – jesselangdon