通常我们都是通过递归的方式将扁平数组转成树形数据,这次偶然看见一位大佬写的非递归方法,记录下来学习一下。人菜就得多学习啊
/**
* @param list 列表
* @param id id-key
* @param pid pid-key
* @param rootid 根id
* @param children children-key
*/
function toTree(list = [], { id = "id", pid = "pid", rootid = "rootid", children = "children" } = {}) {
const parentMap = new Map(),
topNodes = [];
for (const item of list) {
if (parentMap.has(item[id])) {
item[children] = parentMap.get(item[id])[children];
} else {
item[children] = [];
}
parentMap.set(item[id], item);
if (parentMap.has(item[pid])) {
parentMap.get(item[pid])[children].push(item);
} else {
parentMap.set(item[pid], { [children]: [item] })
}
if (String(item[pid]) === rootid) {
topNodes.push(item);
}
}
return topNodes;
}
效果如下:
const data = [
{
id: "1",
pid: "0",
value: 1
},
{
id: "2",
pid: "1",
value: 2
},
{
id: "3",
pid: "2",
value: 3
},
{
id: "4",
pid: "3",
value: 4
}
];
console.log(toTree(data, { rootid: "0" }));