const rootList = [
{ id: 1, name: "父级", parentId: 0 },
{ id: 2, name: "子级", parentId: 1 },
{ id: 3, name: "子级", parentId: 1 }
]
// 普通列表转换树结构
function dataToTree(source, parentId = 0) {
let tree = [];
source.forEach((item) => {
if (item.parentId === parentId) {
// 递归寻找
item.children = dataToTree(source, item.id);
tree.push(item);
}
});
return tree;
}
let res = dataToTree(rootList)
// 树结构转换普通列表
const tree = function (source) {
let res = []
source.forEach(item => {
if (item.children) {
res.push(item, ...tree(item.children))
delete item.children
} else {
res.push(item)
}
})
return res
}
let result = tree(res)
console.log(result)
标签:转换,树结构,res,tree,列表,item,source,parentId
From: https://www.cnblogs.com/mtr-coder/p/17439473.html