gpt4 book ai didi

javascript - 从嵌套的 Javascript 对象中提取和合并数组

转载 作者:行者123 更新时间:2023-11-29 23:53:02 25 4
gpt4 key购买 nike

我有一个 javascript 嵌套对象,如下所示:

input_data = {
"A1":{
"B1":{
"M1" : [
{"E1":"10","E2":"11"},
{"E1":"20","E2":"21"}
],
"M2":[
{"E1":"30","E2":"31"},
{"E1":"40","E2":"41"}
],
"M3":[
{"E1":"50","E2":"51"}
]
}
},
"A2":{
"B2":{
"M1": [
{"E1":"60","E2":"61"},
{"E1":"70","E2":"71"}
],
"M2":[
{"E1":"80","E2":"81"},
{"E1":"90","E2":"91"}
]
}
}
}

我需要将“M1”、“M2”、“M3”下的所有项目提取到一个数组中,即输出应该如下所示:

output_data = [
{"E1":"10","E2":"11"},
{"E1":"20","E2":"21"},
{"E1":"30","E2":"31"},
{"E1":"40","E2":"41"},
{"E1":"50","E2":"51"},
{"E1":"60","E2":"61"},
{"E1":"70","E2":"71"},
{"E1":"80","E2":"81"},
{"E1":"90","E2":"91"}
];

我可以通过以下方式实现:

var output_data = [];
function traverse(obj) {
for (i in obj) {
if (!!obj[i] && typeof(obj[i])=="object") {
if (Array.isArray(obj[i])){
output_data = output_data.concat([], obj[i]);
}
traverse(obj[i] );
}
}
}

traverse(input_data);
console.log(output_data);

有没有更好的方法来提取子数组项并合并为一个?

最佳答案

您可以对嵌套对象使用递归方法。

function flat(object) {
function f(o) {
Object.keys(o).forEach(function (k) {
if (!o[k]) {
return;
}
if (Array.isArray(o[k])) {
result = result.concat(o[k]);
return;
}
if (typeof o[k] === 'object') {
f(o[k]);
}
});
}
var result = [];
f(object);
return result;
}

var input_data = { A1: { B1: { M1: [{ E1: "10", E2: "11" }, { E1: "20", E2: "21" }], M2: [{ E1: "30", E2: "31" }, { E1: "40", E2: "41" }], M3: [{ E1: "50", E2: "51" }] } }, A2: { B2: { M1: [{ E1: "60", E2: "61" }, { E1: "70", E2: "71" }], M2: [{ E1: "80", E2: "81" }, { E1: "90", E2: "91" }] } } };

console.log(flat(input_data));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 从嵌套的 Javascript 对象中提取和合并数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42376260/

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