我有以下JavaScript对象结构。
[
[
null,
"A"
],
[
"A",
"B"
],
[
"A",
"C"
],
[
null,
"D"
],
[
"D",
"E"
],
[
"D",
"F"
],
[
"B",
"G"
]
]
我需要将它排序为以下结构。
[
{
parent: "A",
child : [
{
parent : "B",
child : [
{
parent : "G"
}
]
},
{
parent : "C"
}
]
},
{
parent: "D",
child : [
{
parent : "E"
},
{
parent : "F"
}
]
}
]
答案 0 :(得分:0)
希望这可以帮助你:
var a = [
[
null,
"A"
],
[
"A",
"B"
],
[
"A",
"C"
],
[
null,
"D"
],
[
"D",
"E"
],
[
"D",
"F"
],
[
"B",
"G"
]
];
var result = [];
for(var iter = 0; iter < a.length; iter++){
var ele = a[iter];
// element has no parent
if(!ele[0] || !getParentByName(result,ele[0])){
result.push({ parent: ele[1]});
}
// element has got parent
else if(ele[0] && getParentByName(result,ele[0])){
var parent = getParentByName(result,ele[0]);
if(!parent.child)parent.child=[];
parent.child.push({ parent: ele[1]});
}
}
function getParentByName(result,name){
for(var p=0; p <result.length;p++){
if(result[p].parent == name)return result[p];
for(var c=0; result[p].child && c <result[p].child.length;c++){
if(result[p].child[c].parent == name)return getParentByName(result[p].child,name);
}
}
}
console.log(result);
答案 1 :(得分:0)
您可以直接在结果树中添加父项。但是对于添加孩子,你将不得不使用递归。请参阅以下解决方案。
var result_tree = [];
var test_data = [
[
null,
"A"
],
[
"A",
"B"
],
[
"A",
"C"
],
[
null,
"D"
],
[
"D",
"E"
],
[
"D",
"F"
],
[
"B",
"G"
]
];
function create_tree(test_data) {
test_data.forEach(function (node) {
// create new root parent node if node does not have any parent
if (node[0] === null) {
result_tree.push(
{
parent: node[1],
}
)
}
// else search for existing parent and attach child to it
else {
search_and_attach_child(result_tree, node[0], node[1]);
}
});
}
function search_and_attach_child(tree, parent, child) {
if (!tree) {
return;
}
tree.forEach(function (node) {
if (node.parent === parent) {
if (node.child) {
node.child.push({parent: child})
} else {
node.child = [{parent: child}]
}
} else {
search_and_attach_child(node.child, parent, child);
}
})
}
create_tree(test_data);
console.log(JSON.stringify(result_tree));