如何将平面多分支数据转换为分层JSON? [英] How to convert flat multi-branch data to hierarchical JSON?
问题描述
[
{
"id": "a",
"pid": "a",
"name": "AA",
},
{
"id": "b",
"pid": "a",
"name": "BB",
},
{
"id": "c",
"pid": "a",
"name": "CC",
},
{
"id": "x",
"pid": "b",
"name": "XX",
}
]
以上是我从数据库中获得的数据。每个人都有一个 id
和一个 pid
, pid
点该人员的上级人员的 id
。如果某人的水平最高,则 id
等于 pid
。
Above is the data I got from the database. Every person has an id
and a pid
, pid
points to the person's higher level person's id
. If a person has highest level, the id
equals pid
.
我想将原始数据转换为分层JSON,如下所示:
I want to convert the raw data to hierarchical JSON, like this:
[
{
"id": "a",
"name": "AA",
"child": [
{
"id": "b",
"name": "BB"
"child": [
{
"id": "x",
"name": "XX"
}
]
},
{
"id": "c",
"name": "CC"
}
]
}
]
我正在使用Node.js。
I'm using Node.js.
推荐答案
我建议您创建一棵树并将 id === pid
用作树的根,适用于未排序的数据。
I suggest you to create a tree and take id === pid
as a root for the tree, which works for unsorted data.
它是如何工作的:
How it works:
基本上,对于数组中的每个对象,它使用 id
来构建新对象,而使用 parentid
来创建一个新对象。新对象。
Basically, for every object in the array, it takes the id
for building a new object as parentid
for a new object.
例如:
{ "id": 6, "pid": 4 }
它首先使用 id生成此属性
:
"6": {
"id": 6,
"pid": 4
}
然后带有 pid
:
"4": {
"children": [
{
"id": 6,
"pid": 4
}
]
},
所有对象都经过类似处理后,我们终于得到了一棵树。
and while all objects are similarly treated, we finally get a tree.
如果 id === pid
,找到根节点。这是以后返回的对象。
If id === pid
, the root node is found. This is the object for the later return.
var data = [
{ "id": "f", "pid": "b", "name": "F" },
{ "id": "e", "pid": "c", "name": "E" },
{ "id": "d", "pid": "c", "name": "D" },
{ "id": "c", "pid": "b", "name": "C" },
{ "id": "a", "pid": "a", "name": "A" },
{ "id": "b", "pid": "a", "name": "B" }
],
tree = function (data) {
var r, o = Object.create(null);
data.forEach(function (a) {
a.children = o[a.id] && o[a.id].children;
o[a.id] = a;
if (a.id === a.pid) {
r = a;
} else {
o[a.pid] = o[a.pid] || {};
o[a.pid].children = o[a.pid].children || [];
o[a.pid].children.push(a);
}
});
return r;
}(data);
console.log(tree);
这篇关于如何将平面多分支数据转换为分层JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!