[英]Creating tree object from flat array
I am a little stuck on this. 我对此有些困惑。 I want to create a tree structure from a flat array. 我想从平面数组创建树结构。 Say I have this input: 说我有这个输入:
var input = [
["a","b","c"],
["a", "b","d"],
["e","f","g"],
];
I want to create a tree structure looking like the following: 我想创建一个树形结构,如下所示:
// output:
[
{
id: "a",
children: [
{id: "b", children: [
{id: "c", children: []},
{id: "d", children: []}
]},
]
},
{
id: "e",
children: [
{
id: "f",
children: [{ id: "g", children: []}]
},
]
}
]
One way I was thinking of doing this was having a map of all of the parent and iterate through the input array to set the parent to child mappings. 我想到的一种方式是拥有所有父对象的映射,并遍历输入数组以将父对象设置为子映射。 But I come to problems when trying to actually construct the tree object from that map and avoiding duplicates. 但是在尝试从该映射实际构建树对象并避免重复时遇到了问题。 Any pointers are appreciated, thanks! 任何指针表示赞赏,谢谢!
I found the solution to a problem that is similar to your question. 我找到了与您的问题类似的问题的解决方案。
If you have data that looks like this: 如果您的数据如下所示:
_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"}
]
});
Parameters: 参数:
q
(Array): A query result (see example below) q
(数组):查询结果(请参见下面的示例) id
(String): The name of the id column (Default: "id") id
(字符串):id列的名称(默认值:“ id”) parentid
(String): The name of the ParentItemID column (Default: "parentid") parentid
(字符串):ParentItemID列的名称(默认值:“ parentid”) children
(String): The name of the "children" array to be created in rows that have children (Default: "children") children
(字符串):要在具有子行的行中创建的“ children”数组的名称(默认值:“ children”) Then result should be something like the following structure: 然后结果应该类似于以下结构:
[
{
"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"
}
]
}
]
}
]
Now, _makeTree
codes: 现在, _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; };
References: 参考文献:
I need to create a custom tree data-structure using JavaScript 我需要使用JavaScript创建自定义树数据结构
Creating trees from SQL queries in Javascript 用Javascript从SQL查询创建树
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.