I am working with an array of objects structured as a tree. I have a requirement to add a new property called "dateType" to the objects at the 3rd level.
let tree = [
{
id: 1,
name: "parent1",
children: [
{
id: 2,
name: "child1",
children: [
{ id: 4, name: "subChild1" },
{ id: 5, name: "subChild2" }
]
},
{ id: 3, name: "child2" }
]
}
];
The desired structure should look like this:
let tree = [
{
id: 1,
name: "parent1",
children: [
{
id: 2,
name: "child1",
children: [
{ id: 4, name: "subChild1", dateType: "test" },
{ id: 5, name: "subChild2", dateType: "test" }
]
},
{ id: 3, name: "child2" }
]
}
];
Is there a more efficient way to achieve this, as my current approach requires iterating multiple levels?
custTree(res) {
let result = [];
res.forEach(level1 => {
level1.children.forEach(level2 => {
level2.children.forEach(level3 => {
console.log(level3)//nothing here
//code here
});
});
});
return result;
},
Note: The tree structure is dynamic and always three levels deep, but the update to the "dateType" property should be applied at the last level.