我有这棵树:
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
}