2 回答
TA贡献1772条经验 获得超6个赞
分配和返回必须不同
let parents_children = parents.map(item => {
item.children = data.
filter(stop => stop.parent == item.ID);
return item;
});
// 更好的性能
let result = data2.reduce((map, cur) => {
if (cur.parent === "0") {
// parent
map[cur.ID] = map[cur.ID] || { children: [] };
map[cur.ID] = { ...map[cur.ID], ...cur };
} else {
if (!map[cur.parent]) map[cur.parent] = { children: [] };
map[cur.parent].children.push(cur);
}
return map;
}, {});
let finalResult = [];
for (const key in result) {
finalResult.push(result[key]);
}
console.log(JSON.stringify(finalResult, null, 4));
工作样本:
const data = [
{ ID: 1, parent: "0", title: "Test-1" },
{ ID: 2, parent: "1", title: "Test-1-1" },
{ ID: 3, parent: "0", title: "Test-2" },
{ ID: 4, parent: "0", title: "Test-3" },
{ ID: 5, parent: "4", title: "Test-3-1" },
{ ID: 6, parent: "4", title: "Test-3-2" }
];
let parents = data.filter(item => item.parent == "0");
let parents_children = parents.map(item => {
// create new object
return {
...item,
children : data.filter(stop => stop.parent == item.ID)
};
});
console.log(JSON.stringify(parents_children, null, 4));
console.log(data);
const data2 = [
{ ID: 1, parent: "0", title: "Test-1" },
{ ID: 2, parent: "1", title: "Test-1-1" },
{ ID: 3, parent: "0", title: "Test-2" },
{ ID: 4, parent: "0", title: "Test-3" },
{ ID: 5, parent: "4", title: "Test-3-1" },
{ ID: 6, parent: "4", title: "Test-3-2" }
];
// Better performance
let result = data2.reduce((map, cur) => {
if (cur.parent === "0") {
// parent
map[cur.ID] = map[cur.ID] || { children: [] };
map[cur.ID] = { ...map[cur.ID], ...cur };
} else {
if (!map[cur.parent]) map[cur.parent] = { children: [] };
map[cur.parent].children.push(cur);
}
return map;
}, {});
let finalResult = [];
for (const key in result) {
finalResult.push(result[key]);
}
console.log(JSON.stringify(finalResult, null, 4));
.as-console-row {color: blue!important}
TA贡献2012条经验 获得超12个赞
.map()你忘了从我相信回来。
尝试以下操作:
let parents_children = parents.map(item => {
item.children = data.filter(stop => stop.parent == item.ID)
return item;
});
我希望这有帮助!
添加回答
举报