I have been searching through the internet and cannot find the right word to search so I end up here asking again to all of you seniors in Javascript. The code below is taken from the answer on these question I really don't understand how the method or function work.
var list = [{id: 1,title: 'home',parent: null},{id: 2,title: 'about',parent: null},{id: 3,title: 'team',parent: 2},{id: 4,title: 'company',parent: 2} ];
function treeify(list) {
var treeList = [];
var lookup = {};
list.forEach(function(obj) {
obj['children'] = [];
lookup[obj['id']] = obj;
});
console.log(lookup); // [problem number 1]
list.forEach(function(obj) {
if (obj['parent'] != null) {
lookup[obj['parent']]['children'].push(obj);
} else {
treeList.push(obj);
}
});
console.log(treeList); // [problem number 2]
};
treeify(list);
On problem number 1:
It resulted an object that had already a children on each parent which is supposedly I think that, parent should have an empty array children at that moment. How does it work? Please enlightened me.
On problem number 2
treeList already formed the hierarchy tree. How it happen? it didn't even push the lookup variable to the treeList variable? It only pushes the obj with a parent that is equal to null (which is the root parent).
Hoping for your answer. If you know any blog, article and etc. that may help me understand javascript please don't hesitate to add the link in your answer. Many Thank you!