我的代碼:如何包含數組對象轉換爲對象的對象
function convert(arr, parent) {
var out = [];
for(var i in arr) {
if(arr[i].parent == parent) {
var children = convert(arr, arr[i].id)
if(children.length) {
arr[i].children = children
}
out.push(arr[i])
}
}
return out; //return Object.assign({}, out);tried this, but i lose parents childrens arrays
};
arras = [
{id: 1, name: "parent1", parent: null},
{id: 2, name: "children1", parent: 1},
{id: 3, name: "children2", parent: 1},
{id: 4, name: "parent2", parent: null},
{id: 5, name: "children3", parent: 4},
{id: 6, name: "children4", parent: 4}
]
console.log(convert(arras, null));
如何最終的結果應該
{
parent1: [
{name: "children1"},
{name: "children2"}
],
parent2: [
{name: "children3},
{name: "children4"}
]
}
我的輸出看起來是什麼至今:
[
{id: 1, name: "parent1", parent: null}: [
{id: 2, name: "children1", parent: 1},
{id: 3, name: "children2", parent: 1},
],
{id: 4, name: "parent2", parent: null}: [
{id: 5, name: "children3", parent: 4},
{id: 6, name: "children4", parent: 4}
]
]
所以首先,我必須做的是將主數組轉換爲對象,當我傾向於這樣做時,我失去了兩個父對象數組......還需要更改方式控制檯顯示對象,任何幫助表示讚賞。
功能那種無法處理這個沒有一個父ID子ID,分配所有無與倫比的孩子的名字到一個數組'arras.undefined'這是不是一個好名字屬性。此外,這些孩子的父母身份證在這個過程中會丟失,這將是一個重大失敗。 – Blindman67
@ Blindman67如果輸入數據將包含沒有hape屬性「parent」的記錄,則您注意是正確的。但對我來說,它只是錯誤的輸入數據 –