【转】[JavaScript] 将一组对象生成一个树形结构
来自:kimi.com
以下是一个用 JavaScript 实现的代码示例,用于将一组对象按
pid(父级ID)和 id(当前对象ID)属性建立父子关系。最终会生成一个树形结构的数组。JavaScript复制
// 示例数据
const items = [
{ id: 1, pid: null, name: 'Item 1' },
{ id: 2, pid: 1, name: 'Item 2' },
{ id: 3, pid: 1, name: 'Item 3' },
{ id: 4, pid: 2, name: 'Item 4' },
{ id: 5, pid: null, name: 'Item 5' },
{ id: 6, pid: 5, name: 'Item 6' }
];
// 用于将对象按父子关系组织成树形结构
function buildTree(items) {
const map = new Map(); // 用于存储ID和对象的映射
const tree = []; // 最终的树形结构数组
// 首先将所有对象存入map,方便后续查找
for (const item of items) {
map.set(item.id, { ...item, children: [] }); // 为每个对象添加children属性
}
// 遍历每个对象,根据pid建立父子关系
for (const item of items) {
if (item.pid === null) {
// 如果pid为null,说明是根节点
tree.push(map.get(item.id));
} else {
// 如果有pid,找到对应的父对象,并将其添加到父对象的children数组中
const parent = map.get(item.pid);
if (parent) {
parent.children.push(map.get(item.id));
}
}
}
return tree;
}
// 调用函数并输出结果
const result = buildTree(items);
console.log(JSON.stringify(result, null, 2));
代码说明
-
数据准备:
items是一个数组,包含多个对象,每个对象有id、pid和其他属性。 -
映射存储:使用
Map来存储每个对象,键为id,值为对象本身,并为每个对象添加一个children属性,用于存储子节点。 -
建立关系:
-
遍历每个对象,根据
pid判断其是否为根节点(pid为null)。 -
如果是根节点,直接加入到最终的树形结构数组
tree中。 -
如果不是根节点,则通过
Map找到其父节点,并将其添加到父节点的children数组中。
-
-
输出结果:最终的
tree数组是一个树形结构,可以通过递归遍历等方式进行操作。
输出示例
对于上述示例数据,输出结果为:
JSON复制
[
{
"id": 1,
"pid": null,
"name": "Item 1",
"children": [
{
"id": 2,
"pid": 1,
"name": "Item 2",
"children": [
{
"id": 4,
"pid": 2,
"name": "Item 4",
"children": []
}
]
},
{
"id": 3,
"pid": 1,
"name": "Item 3",
"children": []
}
]
},
{
"id": 5,
"pid": null,
"name": "Item 5",
"children": [
{
"id": 6,
"pid": 5,
"name": "Item 6",
"children": []
}
]
}
]
你可以根据实际需求调整代码逻辑,例如处理更复杂的数据结构或添加额外的属性。
浙公网安备 33010602011771号