我有一棵树:
const tree = {
"1": "root",
"children": [
{
"2": "similar values",
"children": [
{
"3": "similar values info",
"children": [
{
"4": "similar values",
"children": [
{
"5": "similar values",
"children": [
{
"6": "similar values"
}
]
}
]
}
]
}
]
}
]
}我想以这种格式转换数据,这样我就可以用React-Flow进行显示(这里的示例:https://reactflow.dev/examples/layouting/
这是我想要的格式:
[
{
id: '1'
},
{
id: '2'
},
{
id: '3'
},
{
id: '4'
},
{
id: '5'
},
{
id: '6'
},
{ id: 'e12', source: '1', target: '2', type: edgeType, animated: true },
{ id: 'e23', source: '2', target: '3', type: edgeType, animated: true },
{ id: 'e34', source: '3', target: '4', type: edgeType, animated: true },
{ id: 'e45', source: '4', target: '5', type: edgeType, animated: true },
{ id: 'e56', source: '5', target: '6', type: edgeType, animated: true },
];所以最终我需要将它转换成一个数组,获取所有的键作为id,然后根据父/子结构找到源和目标。我非常感谢任何输入,这是我当前的代码:(我认为我至少正确地得到了父对象和源代码),问题就是目标,所以是一种找到孩子的方法。
function getParent(root, id) {
var node;
root.some(function (n) {
if (n.id === id) {
return node = n;
}
if (n.children) {
return node = getParent(n.children, id);
}
});
return node || null;
}
{
id: 'id',
source: Object.keys(getParent(tree, id))[0],
target: '2',
type: edgeType,
animated: true
}发布于 2021-09-02 14:28:21
创建一个对象(未指定),因此这仅适用于一条边。同时也要认识到some并不是真正合适的工具。您需要使用find并将其返回值分配给node (在回调之外)。
无论如何,像这样搜索父级并不是最有效的。你可以遍历输入结构,边走边收集...
下面是你可以做的事情:
const edgeType = "edgeType"; // Dummy
function getNodes({children, ...rest}) {
const [[id, label]] = Object.entries(rest);
return [{ id, data: { label }}].concat((children??[]).flatMap(getNodes));
}
function getEdges({children, ...rest}) {
const [source] = Object.keys(rest);
children ??= [];
return children.map(function ({children, ...rest}) {
const [target] = Object.keys(rest);
return {
id: `e${source}_${target}`,
source,
target,
type: edgeType,
animated: true
}
}).concat(children.flatMap(getEdges));
}
const tree = { "1": "root", "children": [ { "2": "similar values", "children": [ { "3": "similar values info", "children": [ { "4": "similar values", "children": [ { "5": "similar values", "children": [ { "6": "similar values" } ] } ] } ] } ] } ] };
const result = getNodes(tree).concat(getEdges(tree));
console.log(result);
因为在这段代码中edgeType是未知的,所以我用一个虚拟值定义了它。在您的环境中,您不会这样做。
https://stackoverflow.com/questions/69011560
复制相似问题