javascript - 如何从 JSON 数据创建树结构

标签 javascript json tree treeview

我有一个像这样的 JSON 列表:

var arr=[
{
     "text":"text1",
     "id"  :"1",
     //no parent id
 },
{
     "text":"text2",
     "id"  :"2",
     "idParent":"1"
 },
{
     "text":"text3",
     "id"  :"3",
     "idParent":"2"
 },
{
     "text":"text4",
     "id"  :"4",
     "idParent":"1"
 },
{
     "text":"text5",
     "id"  :"5",
      //no parent id
 },
];

我需要像下面这样在层次结构树中转换该列表:

var arr = [
  {
    "text": "Parent 1",
    "id"  : "1",
    "nodes": [
      {
        "text": "Child 1",
        "id"  : "2",
        "parentid"  : "1",
        "nodes": [
          {
            "text": "Grandchild 1",
            "id"  : "4",
            "parentid"  : "2",
          },
          {
            "text": "Grandchild 2",
             "id"  : "8",
            "parentid"  : "2",
          }
        ]
      },
      {
        "text": "Child 2",
        "id"  : "10",
        "parentid"  : "1",
      }
    ]
  },
  {
    "text": "Parent 2",
    "id"  : "19",
    //no parent id
  }
];

只有根 parent 没有“parentid”元素。

我如何在 Javascript 中执行此操作?

预先感谢您的帮助。

最佳答案

无序节点的解决方案。

var arr = [
        { text: "text3", id: "3", parentId: "2" },
        { text: "text2", id: "2", parentId: "1" },
        { text: "text4", id: "4", parentId: "1" },
        { text: "text1", id: "1", /* no parent id */ },
        { text: "text5", id: "5", /* no parent id */ }
    ],
    data = arr.reduce(function (r, a) {
        function getParent(s, b) {
            return b.id === a.parentId ? b : (b.nodes && b.nodes.reduce(getParent, s));
        }

        var index = 0, node;
        if ('parentId' in a) {
            node = r.reduce(getParent, {});
        }
        if (node && Object.keys(node).length) {
            node.nodes = node.nodes || [];
            node.nodes.push(a);
        } else {
            while (index < r.length) {
                if (r[index].parentId === a.id) {
                    a.nodes = (a.nodes || []).concat(r.splice(index, 1));
                } else {
                    index++;
                }
            }
            r.push(a);
        }
        return r;
    }, []);

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

关于javascript - 如何从 JSON 数据创建树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32160294/

相关文章:

javascript - setState方法导致 "Warning: setState(...): Can only update a mounted or mounting component.."错误

javascript - 如何使用 JavaScript 将所有用户输入转换为大写字母?

Json-Opening Yelp Data Challenge的数据集

algorithm - 用于在树中查找支配集的多项式时间算法

c++ - 打印树显示奇怪的字符

algorithm - 蒙特卡洛树搜索算法中的转置表对 UCT 分数的意外影响

javascript - 尝试将远程图像转换为 base64 数据的 CORS 错误

javascript - 如何将html字符串代码转换为将出现在前端的实际html工作代码?

json - 使用 Embarcadero 代码示例通过 TJSONObject 解析有效 JSON 失败并出现异常

json - 在Powershell 2.0中读取JSON对象