从平面数组创建树对象

时间:2015-08-03 19:01:52

标签: javascript

我有点坚持这个。我想从平面数组创建一个树结构。说我有这个输入:

var input = [
    ["a","b","c"],
    ["a", "b","d"],
    ["e","f","g"],
];

我想创建一个如下所示的树结构:

// output:
[
    {
        id: "a",
        children: [
            {id: "b", children: [
                {id: "c", children: []},
                {id: "d", children: []}
            ]},
        ] 
    },
    { 
        id: "e",
        children: [
          {
              id: "f",
              children: [{ id: "g", children: []}]
          },
        ]
    }
]

我想要这样做的一种方法是拥有所有父级的映射并迭代输入数组以将父级设置为子映射。但是当我尝试从该映射实际构造树对象并避免重复时,我遇到了问题。任何指针都表示赞赏,谢谢!

1 个答案:

答案 0 :(得分:2)

我找到了与您的问题类似的问题的解决方案。

<强> _makeTree

如果您的数据如下所示:

_makeTree({ q:
    [
        {"id": 123, "parentid": 0, "name": "Mammals"},
        {"id": 456, "parentid": 123, "name": "Dogs"},
        {"id": 214, "parentid": 456, "name": "Labradors"},
        {"id": 810, "parentid": 456, "name": "Pugs"},
        {"id": 919, "parentid": 456, "name": "Terriers"}
    ]
});

参数:

  • q(数组):查询结果(参见下面的示例)
  • id(字符串):id列的名称(默认值:“id”)
  • parentid(String):ParentItemID列的名称(默认值:“parentid”)
  • children(String):要在具有子项的行中创建的“children”数组的名称(默认值:“children”)

然后结果应该类似于以下结构:

[
    {
        "id": 123,
        "parentid": 0,
        "name": "Mammals",
        "children": [
            {
                "id": 456,
                "parentid": 123,
                "name": "Dogs",
                "children": [
                    {
                        "id": 214,
                        "parentid": 456,
                        "name": "Labradors"
                    },
                    {
                        "id": 810,
                        "parentid": 456,
                        "name": "Pugs"
                    },
                    {
                        "id": 919,
                        "parentid": 456,
                        "name": "Terriers"
                    }
                ]
            }
        ]
    }
]

现在, _makeTree 代码:

var _makeTree = function(options) {
  var children, e, id, o, pid, temp, _i, _len, _ref;
  id = options.id || "id";
  pid = options.parentid || "parentid";
  children = options.children || "children";
  temp = {};
  o = [];
  _ref = options.q;
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    e = _ref[_i];
    temp[e[id]] = e;
    if (temp[e[pid]] != null) {
      if (temp[e[pid]][children] == null) {
        temp[e[pid]][children] = [];
      }
      temp[e[pid]][children].push(e);
    } else {
      o.push(e);
    }
  }
  return o;
};

参考文献:

I need to create a custom tree data-structure using JavaScript

Creating trees from SQL queries in Javascript

_makeTree library