gpt4 book ai didi

javascript - 从平面数组创建树对象

转载 作者:行者123 更新时间:2023-11-29 21:44:11 25 4
gpt4 key购买 nike

我有点卡在这上面。我想从一个平面数组创建一个树结构。假设我有这个输入:

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: []}]
},
]
}
]

我考虑这样做的一种方法是拥有所有父级的映射并遍历输入数组以设置父级到子级的映射。但是当我尝试从该 map 实际构造树对象并避免重复时,我遇到了问题。感谢任何指点,谢谢!

最佳答案

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

_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(字符串):ParentItemID 列的名称(默认:“parentid”)
  • children(字符串):要在具有子项的行中创建的“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

关于javascript - 从平面数组创建树对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31794829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com