我有一個json數組..我想重構json對象..但我無法按預期輸出。我想搜索所有項目或對象並插入父項的子項..我試試那樣如何計算javascript中的對象中的孩子?
https://jsfiddle.net/nk6v0y36/1/
var new_Arry = [];
for (var i = 0; i < arry.length; i++) {
var obj = {};
var childeren = [];
obj.con_id = arry[i].con_id;
obj.children = [{
con_to: arry[i].con_to
}];
new_Arry.push(obj)
}
console.log(new_Arry)
預期輸出:
[{
"con_id": 11,
"children": [{
"con_to": 12
}]
}, {
"con_id": 12,
"children": [{
"con_to": 13
}, {
"con_to": 14
}]
}, {
"con_id": 13,
"children": []
}, {
"con_id": 14,
"children": [{
"con_to": 15
}]
}, {
"con_id": 15,
"children": [{
"con_to": 16
}]
}, {
"con_id": 16,
"children": []
}]
答案後
https://jsfiddle.net/nk6v0y36/7/
答不工作..
你不是檢查ID是否已經存在 – thatOneGuy