Basically I am testing ES6 and wanted to try and return an object of objects from an array of objects, each object in the array has an id and a parent, the id will be the name of the property held within the parent. Simple enough, here is my code:
//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));
This code will return:
{
"animal": {
"dog": {
"labrador": {},
"cocker spaniel": {}
},
"cat": {
"house cat": {},
"outdoor cat": {}
},
"fish": {
"bass": {},
"tuna": {}
},
"human": {
"man": {},
"woman": {}
}
}
}
Now, if we run the following:
//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);
}
it alerts one time saying "Key: animal value: [Object object]" but what I don't understand is why, I would expect it to return with "key: animal value: dog" then "key: animal value: cat" and so on.
you know, basically allowing me to loop through each object inside the object of objects and alert its properties and their values.
Also, if you could tell me this also, how would I access something like:
{}.animal.dog.labrador
If I was looking for something specific like if Labrador had a property called name for example.
I hope that makes sense, I think I am just confusing myself if anything just now but I hope I made clear what I have tried and what I would like to happen.
Cheers, SD