列表和树状数据互转
// 列表数据
[
{
id: 1,
name: '节点1',
// 0表示为顶级节点
parentId: 0
},
{
id: 2,
name: '节点1-1',
parentId: 1
}
...
]
// 树状数据
[
{
id: 1,
name: '节点1',
parentId: 0,
children: [
{
id:2,
name: '节点1-1',
parentId:1
}
]
}
]
const arr = [
{ id: 1, parentId: -1 },
{ id: 11, parentId: 1 },
{ id: 12, parentId: 1 },
{ id: 2, parentId: -1 },
{ id: 21, parentId: 2 },
{ id: 22, parentId: 2 },
{ id: 221, parentId: 22 },
];
列表转树状数据
function listToTree(data) {
const temp = {};
const treeData = [];
for (let i = 0; i < data.length; i++) {
temp[data[i].id] = data[i];
}
// eslint-disable-next-line no-restricted-syntax
for (const i in temp) {
// 假定-1为根id
if (+temp[i].parentId !== -1) {
if (!temp[temp[i].parentId].children) {
temp[temp[i].parentId].children = [];
}
temp[temp[i].parentId].children.push(temp[i]);
} else {
treeData.push(temp[i]);
}
}
return treeData;
}
树状数据转列表
function treeToList(data) {
const res = [];
const dfs = (tree, pid) => {
tree.forEach((item) => {
if (item.children) {
dfs(item.children, item.id);
delete item.children;
}
res.push({ ...item, pid });
});
};
// 假定-1为根id
dfs(data, -1);
return res;
}