【js】json内のすべてのノードの親ノードを探し出す
1140 ワード
例:
入力:
var nodes = { node: 6, left: { node: 5, left: { node: 4 }, right: { node: 3 } }, right: { node: 2, right: { node: 1 } } }
出力:
[ { node: 1, parent: 2 }, { node: 2, parent: 6 }, { node: 3, parent: 5 }, { node: 4, parent: 5 }, { node: 5, parent: 6 }, { node: 6, parent: 0 } ]
入力:
var nodes = { node: 6, left: { node: 5, left: { node: 4 }, right: { node: 3 } }, right: { node: 2, right: { node: 1 } } }
出力:
[ { node: 1, parent: 2 }, { node: 2, parent: 6 }, { node: 3, parent: 5 }, { node: 4, parent: 5 }, { node: 5, parent: 6 }, { node: 6, parent: 0 } ]
var arr=[]
function find(obj,parent){
for(var key in obj){
if(key=='node'){
var j={}
var temp=obj[key]
j[key]=temp
j['parent']=parent
arr.push(j)
}
else find(obj[key],temp)
}
}
//////////////////////////////////////
var nodes = {
node: 6,
left: {
node: 5,
left: {
node: 4
},
right: {
node: 3
}
},
right: {
node: 2,
right: {
node: 1
}
}
}
find(nodes,0)
arr.sort(function(a,b){
return a.node-b.node
})
console.log(arr)
// [ { node: 1, parent: 2 },
// { node: 2, parent: 6 },
// { node: 3, parent: 5 },
// { node: 4, parent: 5 },
// { node: 5, parent: 6 },
// { node: 6, parent: 0 } ]