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);
?
添加回答
舉報