0

我有这棵树:

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 
}
4

1 回答 1

1

创建一个对象(未分配),因此这仅适用于一个边。还要意识到这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中是未知的,我用一个虚拟值定义了它。你不会在你的环境中这样做。

于 2021-09-02T14:28:21.190 回答