数组转树形数据
2022-11-13 19:29:26
2024-11-21 03:42:13
解决方案
js
const nodes = [
{ id: 3, name: '节点C', pid: 1 },
{ id: 6, name: '节点F', pid: 3 },
{ id: 0, name: 'root', pid: null },
{ id: 1, name: '节点A', pid: 0 },
{ id: 8, name: '节点H', pid: 4 },
{ id: 4, name: '节点D', pid: 1 },
{ id: 2, name: '节点B', pid: 0 },
{ id: 5, name: '节点E', pid: 2 },
{ id: 7, name: '节点G', pid: 2 },
{ id: 9, name: '节点I', pid: 5 }
];
function convert(data) {
if (!Array.isArray(data)) {
new Error('data must be an array');
return;
}
let result;
let map = {};
data.forEach(item => {
//id作为key
map[item.id] = item;
});
data.forEach(item => {
// item.pid 为0时 返回underfined
let parent = map[item.pid];
if (parent) {
//如果用children,就直接push,没有就初始化数组
(parent.children || (parent.children = [])).push(item);
} else {
// 这里push的item是pid为0的数据
result = item;
}
});
return result;
}
console.log(convert(nodes));
运行结果
js
{
id: 0,
name: 'root',
pid: null,
children: [
{ id: 1, name: '节点A', pid: 0, children: [Array] },
{ id: 2, name: '节点B', pid: 0, children: [Array] }
]
}
目录