2 回答
TA贡献1818条经验 获得超7个赞
您可以reduce使用一个对象对数组执行操作来存储对每个对象的引用(用于添加子对象)和一个数组来存储结果。
const arr = [
{"id": 123, "parentid": 0, "name": "Mammals"},
{"id": 456, "parentid": 123, "name": "Dogs"},
{"id": 214, "parentid": 456, "name": "Labradors"},
{"id": 810, "parentid": 456, "name": "Pugs"},
{"id": 919, "parentid": 456, "name": "Terriers"}
];
const {res} = arr.reduce((acc,curr)=>{
if(acc.parentMap[curr.parentid]){
(acc.parentMap[curr.parentid].children =
acc.parentMap[curr.parentid].children || []).push(curr);
} else {
acc.res.push(curr);
}
acc.parentMap[curr.id] = curr;
return acc;
}, {parentMap: {}, res: []});
console.log(res);
TA贡献1775条经验 获得超8个赞
我发现更容易理解:
创建数组中所有可能 id 的对象/字典,以及
然后在将孩子附加到父母后通过字典:
const array = [
{ id: 919, parentid: 456, name: "Terriers" },
{ id: 456, parentid: 123, name: "Dogs" },
{ id: 214, parentid: 456, name: "Labradors" },
{ id: 810, parentid: 456, name: "Pugs" },
{ id: 123, parentid: 0, name: "Mammals" },
];
let tree = [], arrayDictionary = {};
// First map the nodes of the array to an object/dictionary where the key is their id
array.forEach((cat) => {
arrayDictionary[cat.id] = cat;
arrayDictionary[cat.id]["children"] = [];
});
// for each entry in the dictionary
for (var entry in arrayDictionary) {
// get all the data for this entry in the dictionary
const mappedElem = arrayDictionary[entry];
// if the element has a parent, add it
if (
mappedElem.parentid && // the dictionary has a parent
arrayDictionary[mappedElem["parentid"]] // and that parent exists
) {
arrayDictionary[mappedElem["parentid"]]["children"].push(mappedElem);
}
// else is at the root level (parentid = null or 0)
else {
tree.push(mappedElem);
}
}
console.log(tree);
添加回答
举报