const jsonArr = [
{ id: 1, name: "a", parentId: null },
{ id: 2, name: "b", parentId: 1 },
{ id: 3, name: "c", parentId: 2 },
{ id: 4, name: "d", parentId: 2 },
{ id: 5, name: "e", parentId: null },
{ id: 6, name: "f", parentId: 4 },
{ id: 7, name: "g", parentId: 5 },
{ id: 8, name: "h", parentId: 1 },
];
[
{
id: 1,
name: "a",
parentId: null,
children: [
{
id: 2,
name: "b",
parentId: 1,
children: [
{ id: 3, name: "c", parentId: 2, children: [] },
{ id: 4, name: "d", parentId: 2, children: [
{ id: 6, name: "f", parentId: 4, children: [] },
]}
]
}
]
},
......
]
对于只有两层的数据,可以使用常规遍历
function getTree(target) {
const parents = target.filter(p => p.parentId === null);
const childs = target.filter(c => c.parentId !== null);
parents.forEach(p => {
childs.forEach(c => {
if(p.id === c.parentId) {
p.children = p.children || [];
p.children.push(c);
}
})
})
return parents;
}
对于多层的数据,使用递归
function convertTree(target) {
const convertFn = (target, pId, result) => {
target.forEach(item => {
if(item.parentId === pId) {
result.push(item);
}
});
result.forEach(res => {
res.children = [];
convertFn(target, res.id, res.children);
})
return result;
}
return convertFn(target, null, []);
}
const treeData = convertTree(jsonArr);
console.log("转化后的树形结构数组:", treeData)