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

时间:2019-06-14 15:32:15

标签: javascript arrays json tree converters

我想将此json /对象转换为下面的特定结构,以允许我使用treeList组件。

我尝试构建一个递归函数,但尚未找到解决方案。 谢谢您的帮助

const data = {
  parent1: {
    child1: { bar: "1" },
    child2: "2"
  },
  parent2: {
    child1: "1"
  }
}

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"
      }
    ]
  }
]

2 个答案:

答案 0 :(得分:1)

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

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 :(得分:0)

只分享样本,与您的样本略有不同。但这给您带递归功能的提示。

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>');