将连接元素的数组转换为树
Transform an array of connected elements to a tree
给定一个连接元素数组,我怎样才能创建一个子元素数组?
const array = [
{id: "dndnode_0", ...},
{id: "dndnode_1", ...},
{id: "dndnode_2", ...},
{id: "dndnode_3", ...}
]
const connections = [
{source:'dndnode_0', target:'dndnode_1'},
{source:'dndnode_0', target:'dndnode_2'},
{source:'dndnode_2', target:'dndnode_3'},
]
我正在使用 react-flow-renderer 库顺便说一下。
我想要这样的东西
const array = [
{
id: "dndnode_0",
children: [
{id: "dndnode_1", ...},
{id: "dndnode_2", ...}
]
},
{
id: "dndnode_2",
children: [
{id: "dndnode_3", ...}
]
}
]
您可以构建一个以节点 ID 为键的映射,其中对应的值是具有附加(空)children
属性.
的节点对象
然后在遍历连接时填充这些 children
属性。
最终从该映射中获取值,并可选择仅保留具有子节点的节点:
const nodes = [
{id: "dndnode_0" },
{id: "dndnode_1" },
{id: "dndnode_2" },
{id: "dndnode_3" }
]
const connections = [
{source:'dndnode_0', target:'dndnode_1'},
{source:'dndnode_0', target:'dndnode_2'},
{source:'dndnode_2', target:'dndnode_3'},
]
const map = new Map(nodes.map(node => [node.id, {...node, children: []}]));
for (const {source, target} of connections) map.get(source).children.push(target);
const tree = [...map.values()].filter(node => node.children.length);
console.log(tree);
给定一个连接元素数组,我怎样才能创建一个子元素数组?
const array = [
{id: "dndnode_0", ...},
{id: "dndnode_1", ...},
{id: "dndnode_2", ...},
{id: "dndnode_3", ...}
]
const connections = [
{source:'dndnode_0', target:'dndnode_1'},
{source:'dndnode_0', target:'dndnode_2'},
{source:'dndnode_2', target:'dndnode_3'},
]
我正在使用 react-flow-renderer 库顺便说一下。
我想要这样的东西
const array = [
{
id: "dndnode_0",
children: [
{id: "dndnode_1", ...},
{id: "dndnode_2", ...}
]
},
{
id: "dndnode_2",
children: [
{id: "dndnode_3", ...}
]
}
]
您可以构建一个以节点 ID 为键的映射,其中对应的值是具有附加(空)children
属性.
然后在遍历连接时填充这些 children
属性。
最终从该映射中获取值,并可选择仅保留具有子节点的节点:
const nodes = [
{id: "dndnode_0" },
{id: "dndnode_1" },
{id: "dndnode_2" },
{id: "dndnode_3" }
]
const connections = [
{source:'dndnode_0', target:'dndnode_1'},
{source:'dndnode_0', target:'dndnode_2'},
{source:'dndnode_2', target:'dndnode_3'},
]
const map = new Map(nodes.map(node => [node.id, {...node, children: []}]));
for (const {source, target} of connections) map.get(source).children.push(target);
const tree = [...map.values()].filter(node => node.children.length);
console.log(tree);