JS script Parent childrent
by youssef moudine
JavaScript
var result = [
{_id: '#1', libelle: 'A'},
{_id: '#2', libelle: 'B'},
{_id: '#2.1', libelle: 'B1', parent: '#2'},
{_id: '#2.2', libelle: 'B2', parent: '#2'},
{_id: '#2.2.1', libelle: 'B2.1', parent: '#2.2'},
{_id: '#2.2.1.1', libelle: 'B2.1.1', parent: '#2.2.1'},
{_id: '#3', libelle: 'C'},
{_id: '#4', libelle: 'D'},
{_id: '#4.1', libelle: 'D1', parent: '#4'} /**/
];
var childrents = [];
var levels = [];
var parent_less = {};
// separate childrents from parentLess nodes
result.forEach( item => {
if(item.parent != undefined){
childrents.push(item);
}else{
parent_less[item._id] = item;
}
});
// add parentLess as first element in levels
levels.push(parent_less);
// start working on childrents
if(childrents.length) {
var nbr_of_null = -1
while(childrents.length >= nbr_of_null){
var tmp_obj = {};
var last_level = levels[levels.length-1];
childrents.forEach( (child, index) => {
// child parent is in last level
if(child != null && last_level.hasOwnProperty(child.parent)){
// add the child in a new level
tmp_obj[child._id] = childrents.splice(index, 1, null)[0];
}else{
nbr_of_null++;
}
});
levels.push(tmp_obj);
}
}
// start including each child in his parent
while(levels.length > 1){
var bottom_level = levels.pop();
var before_bottom_level = levels[levels.length - 1];
// loop throw child of bottom level and afect each one of them to his parent
Object.keys(bottom_level).forEach(key=>{
var child = bottom_level[key];
if (!before_bottom_level[child.parent].hasOwnProperty('childrents')){
before_bottom_level[child.parent].childrents = [];
}
before_bottom_level[child.parent].childrents.push(child);
});
}
result = [];
Object.keys(levels[0]).forEach(key => {
result.push(levels[0][key])
});
console.log(JSON.stringify(levels, null, 2));