I have a flat list (array of objects), like next one:
var myList = [
{id:1, name:"ABC", type:"level_1"},
{id:2, name:"XYZ", type:"level_1"},
{id:1, name:"ABC_level 2", type:"level_2", level_one_id:1},
{id:2, name:"XYZ_level 2", type:"level_2", level_one_id:2},
{id:1, name:"ABC_level 3", type:"level_3", level_two_id:1},
{id:2, name:"XYZ_level 3", type:"level_3", level_two_id:2},
];
Then, I have to group them in such a way that I can create a hierarchy of levels (which I tried to do in the below lines of code):
var myList = [
{id:1, name:"ABC", type:"level_1"},
{id:2, name:"XYZ", type:"level_1"},
{id:1, name:"ABC_level 2", type:"level_2", level_one_id:1},
{id:2, name:"XYZ_level 2", type:"level_2", level_one_id:2},
{id:1, name:"ABC_level 3", type:"level_3", level_two_id:1},
{id:2, name:"XYZ_level 3", type:"level_3", level_two_id:2},
];
var myNestedList = {
levels: []
};
//-----------pushing level1----------
myList.forEach((res => {
if (res.type == "level_1") {
myNestedList.levels.push(res);
}
}));
//-----------pushing level 2---------
myNestedList.levels.forEach((res) => {
myList.forEach((val) => {
if (val.type == "level_2" && val.level_one_id == res.id) {
res["level_2"] = [] || res["level_2"];
res["level_2"].push(val);
}
})
})
//-----------pushing level 3---------
myNestedList.levels.forEach((res) => {
res["level_2"].forEach((val) => {
myList.forEach((lastlevel) => {
if (lastlevel.type == "level_3" && lastlevel.level_two_id == val.id) {
val["level_3"] = [] || val["level_3"];
val["level_3"].push(lastlevel);
}
})
})
})
console.log(myNestedList);
Although I'm able to achieve the result, I'm sure this code can be more precise and meaningful. Can we make use of lodash here and get this code shorter?
Any help would be much appreciated. Thanks!
level_one_idinstead of a parent property?level_one_id: this will indicate me of the parent id and then I'll be able to group them accordingly.parentfield, it would make life quite a bit easier to work with. But the repeated ids across levels would likely still cause problems.parentfield, I have to loop them anyway with above code.{id:2, name:"XYZ_level 2", type:"level_2", level_one_id:2}belongs under{id:2, name:"XYZ", type:"level_1"}and not under{id:1, name:"ABC", type:"level_1"}? Just the coincidence of the names XYZ vs ABC?