形成树结构
递归(不推荐)
js
/**
* 递归查找,获取children
*/
const getChildren = (data, result, pid) => {
for (const item of data) {
if (item.pid === pid) {
const newItem = { ...item, children: [] };
result.push(newItem);
getChildren(data, newItem.children, item.id);
}
}
};
/**
* 转换方法
*/
const arrayToTree = (data, pid) => {
const result = [];
getChildren(data, result, pid);
return result;
};对象引用
js
function arrayToTree(items) {
const result = []; // 存放结果集
const itemMap = {}; //
for (const item of items) {
const id = item.id;
const pid = item.pid;
if (!itemMap[id]) {
itemMap[id] = {
children: [],
};
}
itemMap[id] = {
...item,
children: itemMap[id]["children"],
};
const treeItem = itemMap[id];
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
};
}
itemMap[pid].children.push(treeItem);
}
}
return result;
}js
function toTree(arr, rootId) {
let obj = {};
let tree = [];
for (let i of arr) {
const { id, pid } = i;
if (!obj[id]) {
obj[id] = {
// ...i,
children: [],
};
}
obj[id] = {
...i,
children: obj[id].children,
};
if (pid === rootId) {
tree.push(obj[id]);
} else {
if (!obj[pid]) {
obj[pid] = {
children: [],
};
}
obj[pid].children.push(obj[id]);
}
}
return tree;
}
JStar