const rootList = [
{ id: 1, parent: null, text: '菜单1' },
{ id: 11, parent: 1, text: '菜单1-1' },
{ id: 12, parent: 1, text: '菜单1-2' },
{ id: 2, parent: null, text: '菜单2' },
{ id: 21, parent: 2, text: '菜单2-1' },
{ id: 22, parent: 2, text: '菜单2-2' },
]
思路:使用递归将数据拼成一个树状数据;
1.首先传入参数id为null,使用for循环,判断如果item里面的item.parent===id,此时的id为null,如果是true,则将符合条件的item添加的新的数组里
2.使用循环,给新数组里面添加children字段,调用写好的递归,参数1:源数据,2:i.id;3:i.children;返回新数组,调用该递归传参
代码如下:第一次循环会得到一个普通数组,第二次会得到带有children的数组
function getTreeList(rootList, id, newArr) {
for (const item of rootList) {
if (item.parent === id) {
newArr.push(item)
}
}
console.log(newArr);
//给数组里面再添加一个children的空数组
for (const i of newArr) {
i.children = [];
getTreeList(rootList, i.id, i.children);
if (i.children.length == 0) {
delete i.children
}
}
console.log(newArr);
return newArr
}
//将数据传入,此时id为null,并且传入一个空数组
const res = getTreeList(rootList, null, []);
console.log('最终返回的数据', res);