如何在JS中将JSON转换为树状数组?

3
我想将这个json/object转换为下面的特定结构,以便我可以使用treeList组件。
我尝试构建了一个递归函数,但是我还没有找到解决方案。谢谢你的帮助。
const data = {
  parent1: {
    child1: { bar: "1" },
    child2: "2"
  },
  parent2: {
    child1: "1"
  }
}

to

const treeData = [
  {
    title: "parent1",
    key: "parent1",
    children: [
      {
        title: "child1",
        key: "child1",
        children: [{ title: "bar", key: "bar", value: "1" }]
      },
      {
        title: "child2",
        key: "child2",
        value: "2"
      }
    ],
  },
  {
    title: "parent2",
    key: "parent2",
    children: [
      {
        title: "child1",
        key: "child1",
        value: "1"
      }
    ]
  }
]

1
你的treeData2对象中包含了同样的键"title"、"key"和"children",这是不合法的。 - Saurabh Mistry
我犯了一个错误,现在已经修复了 :) 谢谢 - Vincent Miquel
2个回答

2
您可以采用迭代和递归的方法。

function getNodes(object) {
    return Object
        .entries(object)
        .map(([key, value]) => value && typeof value === 'object'
            ? { title: key, key, children: getNodes(value) }
            : { title: key, key, value }
        );
}

const data = { parent1: { child1: { bar: "1" }, child2: "2" }, parent2: { child1: "1" } },
    result = getNodes(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


1
哇!太棒了,这正是我一直在寻找的!非常感谢! - Vincent Miquel
你太棒了! - HenonoaH

1

我只是分享一个示例,与你的略有不同。但它可以通过递归函数给你一些提示。

https://jsfiddle.net/segansoft/7bdxmys4/1/

function getNestedChildren(arr, parent) {
  var out = []
  for (var i in arr) {
    if (arr[i].parent == parent) {
      var children = getNestedChildren(arr, arr[i].id)

      if (children.length) {
        arr[i].children = children
      }
      out.push(arr[i])
    }
  }
  return out
}


var flat = [{
    id: 1,
    title: 'hello',
    parent: 0
  },
  {
    id: 2,
    title: 'hello',
    parent: 0
  },
  {
    id: 3,
    title: 'hello',
    parent: 1
  },
  {
    id: 4,
    title: 'hello',
    parent: 3
  },
  {
    id: 5,
    title: 'hello',
    parent: 4
  },
  {
    id: 6,
    title: 'hello',
    parent: 4
  },
  {
    id: 7,
    title: 'hello',
    parent: 3
  },
  {
    id: 8,
    title: 'hello',
    parent: 2
  }
]


var nested = getNestedChildren(flat, 0)

document.write('<pre>' + JSON.stringify(nested, 0, 4) + '</pre>');


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接