I am working on creating a new function called customAdd() that will build a nested tree structure like the one shown below:
let obj = []
let obj1 = {
key: "detail1Tests",
id: "94d3d1a2c3d8c4e1d77011a7162a23576e7d8a30d6beeabfadcee5df0876bb0e"
}
let obj2 = {key: "detail1Tests.detail2Tests", id: "5b091b37a9efc9d0567a4beac0bb20fcdf9796f4b71e239da6ac0c53e3488838"}
let obj3 = {key: "detail1Tests.detail2Tests.detail3Tests", id: "0b60c29d6e309be95ef33b0ad137623c5712a9a47613ce5e561871001c71bd3b"}
let result = this.customAdd(obj, obj1);
console.log(result);
let result1 = this.customAdd(result, obj2);
console.log(result1);
let result2 = this.customAdd(result1, obj3);
console.log(result2);
};
The expected output for 'result' should be:
children: {
detail1Tests: [{
id: " 94d3d1a2c3d8c4e1d77011a7162a23576e7d8a30d6beeabfadcee5df0876bb0e "
}]
'result1' should look like this:
children: {
detail1Tests: [{
id: " 94d3d1a2c3d8c4e1d77011a7162a23576e7d8a30d6beeabfadcee5df0876bb0e "
children: {
detail1Tests.detail2Tests: [{
id: "5b091b37a9efc9d0567a4beac0bb20fcdf9796f4b71e239da6ac0c53e3488838"
}
]
}
}]
Finally, 'result2' should resemble:
children: {
detail1Tests: [{
id: " 94d3d1a2c3d8c4e1d77011a7162a23576e7d8a30d6beeabfadcee5df0876bb0e "
children: {
detail1Tests.detail2Tests: [{
id: "5b091b37a9efc9d0567a4beac0bb20fcdf9796f4b71e239da6ac0c53e3488838"
children: {
detail1Tests.detail2Tests.detail3Tests: [{
id: "0b60c29d6e309be95ef33b0ad137623c5712a9a47613ce5e561871001c71bd3b"
}
]
}
}
]
}
}]
As you can see, the function I've built only works on the first level of nesting. If you have any suggestions on how to extend it to deeper levels, please let me know.
customAdd(obj, subObj){
let obj2 = {children: {[subObj.key]: [{id: subObj.id}] }}
if(obj.children){
let obj3 = obj.children;
var kyz = Object.keys(obj3);
let obj4 = obj3[kyz[0]]
this.customAdd(obj4, subObj)
}
else {
return {...obj,...obj2};
}
}
Any insights on how to achieve deeper nesting are welcome.