如何从JSON数据创建树结构 [英] How to create a tree structure from JSON data
本文介绍了如何从JSON数据创建树结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在JSON中有一个像这样的列表:
I have a list in JSON like this one:
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
},
];
我需要在层次结构树中转换该列表,如下所示:
And I need to convert that list in a hierarchy tree like the following:
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
}
];
只有根父母没有parentid元素。
Only the root parents have no "parentid" element.
¿我如何在Javascript中执行此操作?
¿How can I do this in 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>');
这篇关于如何从JSON数据创建树结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文