在实际的业务或者说面试,会有将树形转为平铺,或者是平铺转换为树形的需求,下面我们来写一下两者转化的区别.
首先给大家介绍一下数据结构展现的方式
这是树形结构数据:
const arr= [{
id: 1,
name: 'A',
children: [{
id: 11,
name: 'A1',
children: [{ id: 111, name: 'a1' }]
}, {
id: 12,
name: 'A2',
children: [{ id: 121, name: 'a2' }]
}]
}, {
id: 2,
name: 'B',
children: [{
id: 21,
name: 'b1',
children: [{ id: 211, name: 'b1' }]
},
{
id: 22,
name: 'b2',
children: [{ id: 221, name: 'b2' }]
}]
}];
这是平铺结构数据
const arr = [
{ pid: null, id: 1, name: 'A' },
{ pid: 1, id: 11, name: 'A1' },
{ pid: 11, id: 111, name: 'a1' },
{ pid: 1, id: 12, name: 'A2' },
{ pid: 12, id: 121, name: 'a2' },
{ pid: null, id: 2, name: 'B' },
{ pid: 2, id: 21, name: 'B1' },
{ pid: 21, id: 211, name: 'b1' },
{ pid: 2, id: 22, name: 'B2' },
{ pid: 22, id: 221, name: 'b2' }
]
下面是转换的代码
平铺转换为树形
function setTree(data, pid = null, res = []) {
data.forEach(item => {
res.push({ pid: pid, id: item.id, name: item.name });
if (item.children && item.children.length !== 0) {
setTree(item.children, item.id, res);
}
});
return res;
};
var arr1 = treeToArr(arr);
console.log(arr1);
树形转换为平铺
function setArr(arr, pid = null) {
const res = [];
arr.forEach(item => {
if (item.pid === pid) {
const children = setArr(arr.filter(v => v.pid !== pid), item.id);
if (children.length) {
res.push({ ...item, children })
} else {
res.push({ ...item })
}
}
});
return res;
};
const arr1 = setArr(arr);
console.log(JSON.stringify(arr1, null, 2));