转换数组中的树以使用 React Flow 和 Dagre 显示

Transform Tree in Array to display with React Flow and Dagre

我有这棵树:

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,并根据 parent/child 结构找到源和目标。我将不胜感激任何输入,这是我当前的代码:(我想我至少得到了 parent 和正确的来源),问题是目标,所以找到 children 的方法。

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 
}

创建一个对象(未分配),因此这将仅用于一个边缘。还要意识到 some 并不是真正正确的工具。您需要使用 find 并将其 return 值分配给 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 是未知的,我用一个虚拟值定义了它。你不会在你的环境中这样做。