基本上我測試ES6,並希望嘗試和返回的對象數組中的對象的對象,數組中的每個對象有一個ID和父母,ID將是在父母的財產。夠簡單了,這裏是我的代碼:問題與對象的對象
//an array of objects
let animals = [{
id: "animal",
parent: null
}, {
id: "dog",
parent: "animal"
}, {
id: "cat",
parent: "animal"
}, {
id: "fish",
parent: "animal"
}, {
id: "labrador",
parent: "dog"
}, {
id: "cocker spaniel",
parent: "dog"
}, {
id: "bass",
parent: "fish"
}, {
id: "tuna",
parent: "fish"
}, {
id: "house cat",
parent: "cat"
}, {
id: "outdoor cat",
parent: "cat"
}, {
id: "human",
parent: "animal"
}, {
id: "man",
parent: "human"
}, {
id: "woman",
parent: "human"
}];
//a recursive function to build our object of objects tree
let makeTreeOfCategories = (categories, parent) => {
let parentNode = {};
categories
.filter(category => category.parent === parent)
.forEach(category => parentNode[category.id] =
makeTreeOfCategories(categories, category.id));
return parentNode;
};
console.log(JSON.stringify(makeTreeOfTrees(animals, null), null, 2));
該代碼將返回:
{
"animal": {
"dog": {
"labrador": {},
"cocker spaniel": {}
},
"cat": {
"house cat": {},
"outdoor cat": {}
},
"fish": {
"bass": {},
"tuna": {}
},
"human": {
"man": {},
"woman": {}
}
}
}
現在,如果我們運行以下命令:
//call our object and store in a variable
let obj = makeTreeOfCategories(animals, null);
//loop through the object and alert each child item and its children
for (var key in obj) {
var val = obj[key];
alert("Key: " + key + " value:" + val);
}
它會提醒一次說「重點:動物價值:[對象對象]「,但我不明白的是爲什麼,我期望它會以」關鍵:動物價值:狗「,然後」關鍵:動物價值:貓「等等來回報。
你知道,基本上讓我遍歷對象的對象內的每個對象,並提醒其屬性和它們的值。
而且,如果你能告訴我這也是,我將如何訪問是這樣的:
{}.animal.dog.labrador
如果我一直在尋找一些具體的事情一樣,如果拉布拉多有個名字叫例如財產。
我希望是有道理的,我想我只是混淆自己如果有什麼剛纔,但我希望我清楚我曾嘗試和我想的事情發生。
乾杯, SD
可能重複( http://stackoverflow.com/q/5612787/1048572)或[爲什麼'[object object]'提到「對象」兩次?](http://stackoverflow.com/q/29847665/1048572) – Bergi