【问题标题】:How to convert json to tree array in JS?如何在JS中将json转换为树数组?
【发布时间】:2019-10-29 06:35:46
【问题描述】:

我想将此 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"
      }
    ]
  }
]

【问题讨论】:

  • 您的 treeData2 在单个对象中包含相同的键 "title","key","children" 两次,这是无效的
  • 我犯了一个错误,现在已经修复了:) thx

标签: javascript arrays json tree converters


【解决方案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; }

【讨论】:

  • 哇!太棒了,这正是我一直在寻找的!非常感谢!
  • 你成功了!
【解决方案2】:

只是分享样本,与你的略有不同。但它给你一个递归函数的提示。

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

【讨论】:

    猜你喜欢
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    相关资源
    最近更新 更多