gpt4 book ai didi

javascript - 使用 Javascript 和下划线循环嵌套对象和数组

转载 作者:行者123 更新时间:2023-12-03 07:07:33 24 4
gpt4 key购买 nike

我正在尝试访问嵌套在数组中的对象。我从这个 JSON 对象(派生自 XML 数据库输出)开始:

{"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

}

我刚刚得到一组未定义的结果。我花了几个小时尝试改变语法来获取嵌套的“访问”对象,但我似乎无法弄清楚。

非常感谢这位新手的任何帮助!

最佳答案

在你的 buildVisitIDArray 函数中,你试图获取 target_metrics[i].visits[1] ,就好像它是一个数组一样,但它实际上是一个对象,所以你应该这样使用它:

function buildVisitIDArray(target_metrics) {
attrList = [];
for(var i=0; i<target_metrics.length; i++) {
var visit_records = target_metrics[i].visits; // Removed the array call ([1])
console.log(visit_records);
for(visit_record in visit_records) {
attrList.push(_.pluck(visit_records[visit_record], "visit_id"));
}
}
return attrList;
}

希望有帮助:)

关于javascript - 使用 Javascript 和下划线循环嵌套对象和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36751064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com