题目:
将一维数组,转化成嵌套的tree
const arr = [
{ id: 1, title: "child1", parentId: 0 },
{ id: 2, title: "child2", parentId: 0 },
{ id: 3, title: "child1_1", parentId: 1 },
{ id: 4, title: "child1_2", parentId: 1 },
{ id: 5, title: "child2_1", parentId: 2 }
]
const buildChildrenArr = (arr) => {
const res = [];
const map = {};
for ( let i = 0; i < arr.length; i++) {
map[arr[i].id] = { ...arr[i], children: []};
const key = arr[i].id;
if (!map[key].parentId) {
res.push(map[key])
} else {
const parentId = map[key].parentId
if (parentId === map[parentId].id) {
map[parentId].children.push(map[key])
}
}
}
return res;
};
console.log('buildChildrenArr', buildChildrenArr(arr));
也能够用递归的形式写,等我钻研分明了再补充
发表回复