Write a recursive function makeTree(categories, parent)
that takes an array of
categories objects, each of which have an id property, and a parent property and
returns a nested tree of those objects using the parent properties to construct
the tree.
A parent value of null means you are at the bottom of the tree and the category has no parent, so the default value parent is be null if no parent is provided.
Example 1:
Given an array of objects with id properties to create our tree:
const categories1 = [
{ id: 'animals', 'parent': null },
{ id: 'mammals', 'parent': 'animals' }
];
const tree1 = makeTree(categories1, null);
We should return a tree like this:
{
animals: {
mammals: {}
}
}
Example 2: Now imagine we have a database that returns a bunch of rows of data:
const categories2 = [
{ id: 'animals', 'parent': null },
{ id: 'mammals', 'parent': 'animals' },
{ id: 'cats', 'parent': 'mammals' },
{ id: 'dogs', 'parent': 'mammals' },
{ id: 'chihuahua', 'parent': 'dogs' },
{ id: 'labrador', 'parent': 'dogs' },
{ id: 'persian', 'parent': 'cats' },
{ id: 'siamese', 'parent': 'cats' }
];
Then we call the function with the categories:
const tree2 = makeTree(categories2, null);
The call above should return the tree below:
{
animals: {
mammals: {
dogs: {
chihuahua: {},
labrador: {}
},
cats: {
persian: {},
siamese: {}
}
}
} }
I have written ten different things but this is an example of one of my current failures, This is a practice problem but I cannot figure it out at all. I am not sure how to check through the second example object and find the correct keys to put everything in its place. I have thought about iterating backwards to create the individual animals and then place them into the parent objects one by one, but I cannot think of a way to do so.
const makeTree = (categories, parent,obj={}) =>
{
if (categories.length === 0) return obj;
let nextObj = categories[0];
if (nextObj['parent'] === null) obj[nextObj['id']] = {};
else {
var cKey = nextObj['id'];
obj[nextObj['parent']] = Object.assign(cKey);
}
categories.shift();
return makeTree(categories, parent, obj);
};