json 递归生成一个嵌套对象,给定一个对象数组和一个子对象数组?

ars1skjm  于 2023-01-27  发布在  其他
关注(0)|答案(1)|浏览(175)

我正在尝试递归地创建一个嵌套对象。下面是示例数据:

"reactions": [
    {
      "name": "Ester amidation",
      "target": "Data #1",
      "sources": ["Data #2", "Data #3"],
    },
    {
      "name": "Buchwald-Hartwig amination with amide",
      "target": "Data #4",
      "sources": ["Data #5", "Data #1"], // BECAUSE Data #1 is a target AND in sources for Data #4, we should nest it as a child of Data #4
    }
  ]

对于target,我试图得到一个输出如下的东西:

{
    name: "My Route 1",
    children: [
      {
        name: "Data #4",
        children: [
          {
            name: "Data #5",
            children: []
          },
          {
            name: "Data #1",
            children: [
                {
                    name: "Data #2",
                    children: []
                },
                {
                    name: "Data #3",
                    children: []
                }
                
            ]
          },
        ],
      },
    ],
  };

我尝试过类似这样的方法,但在处理数组时我感到困惑:

function createNestedTree(objects, target = null) {
    const children = objects.filter(o => o.target === target);
    if (!children.length) {
        return null;
    }
    return children.map(child => ({
        ...child,
        children: createNestedTree(objects, child.id)
    }));
}

有人知道如何创建一个算法吗?非常感谢!

wlzqhblo

wlzqhblo1#

你可以先迭代数据来创建目标对象(用空的children数组),然后在一个以名称为键的Map中引用它们,然后迭代数据来填充那些children数组,同时将子对象标记为不是根,返回剩下的根。
下面是一个可能的实现:

function makeTree(reactions) {
    const map = new Map(reactions.flatMap(({target, sources}) => 
        [target, ...sources].map(name => [name, { name, children: [] }])
    ));
    const roots = new Map(map);
    for (const {target, sources} of reactions) {
        for (const source of sources) {
            map.get(target).children.push(map.get(source));
            roots.delete(source);
        }
    }
    return [...roots.values()];
}

const reactions = [{"name": "Ester amidation","target": "Data #1","sources": ["Data #2", "Data #3"],},{"name": "Buchwald-Hartwig amination with amide","target": "Data #4","sources": ["Data #5", "Data #1"]}];  
const result = makeTree(reactions);
console.log(result);

相关问题