给出如下数据结构,进行数据格式转换,父子集合形式的数据
let data = [
{
id: 1,
name: "目录1",
parentId: 0,
},
{
id: 2,
name: "目录1-1",
parentId: 1,
},
{
id: 3,
name: "目录1-2",
parentId: 1,
},
{
id: 4,
name: "目录1-1-1",
parentId: 2,
},
{
id: 5,
name: "目录1-1-2",
parentId: 2,
},
{
id: 6,
name: "目录2",
parentId: 0,
},
{
id: 7,
name: "目录2-1",
parentId: 6,
},
{
id: 8,
name: "目录2-2",
parentId: 6,
},
];
转换后的数据格式如下:
[
{
id: 1,
name: "目录1",
parentId: 0,
children: [
{
id: 2,
name: "目录1-1",
parentId: 1,
children: [
{ id: 4, name: "目录1-1-1", parentId: 2 },
{ id: 5, name: "目录1-1-2", parentId: 2 },
],
},
{ id: 3, name: "目录1-2", parentId: 1 },
],
},
{
id: 6,
name: "目录2",
parentId: 0,
children: [
{ id: 7, name: "目录2-1", parentId: 6 },
{ id: 8, name: "目录2-2", parentId: 6 },
],
},
];
代码实现:
方式一:
1.对数据进行处理,构建成以数据id为键值的object对象
data.forEach(item => {
mapData[item.id] = item;
});
2.对原始数据进行循环,并判断
let parent = mapData[item.parentId];
if (parent) {
parent.children = parent.children || [];
parent.children.push(item);
} else {
res.push(item);
}
3.返回结果
实现方式二:
利用reduce和递归实现
const children = array2Tree(data, cur.id);
if (children.length) {
cur.children = children;
}
详细资源