我有:
[
{"Name": "One",
"ID": "1",
"Child": [
{ "ChildName": "Alpha"},
{"ChildName": "Beta"}
]
},
{"Name": "Two",
"ID": "1",
"Child": [
{ "ChildName": "Gamma"},
{"ChildName": "Delta"}
]
}
]
我在寻找什么:
[
{ "ChildName": "Alpha",
"ID": "1"},
{ "ChildName": "Beta",
"ID": "1"},
{ "ChildName": "Gamma",
"ID": "2"},
{ "ChildName": "Delta",
"ID": "2"}
]
大量搜索会给出“你不能”或“这是一个 JavaScript 函数”。 但一定有一种优雅的方法来解决这个常见的数据处理问题吗?
试试这个
var newObj = [];
data.forEach((item) => {
item.Child.forEach((ch) => {
var obj = {};
obj.ChildName = ch.ChildName;
obj.ID = item.ID;
newObj.push(obj);
});
});
console.log(JSON.stringify(newObj));
结果
[
{"ChildName":"Alpha","ID":"1"},
{"ChildName":"Beta","ID":"1"},
{"ChildName":"Gamma","ID":"2"},
{"ChildName":"Delta","ID":"2"}
]