On each button click, I aim to add an object as a child of the last existing object.
This is the code snippet I currently have:
const Myarray = [
{ id: 1, child:[] }
]
handleArrayDepth = (Myarray) => {
Myarray.map(arrayitem => {
let id = arrayitem.id;
id++;
arrayitem.child.push({
id: id,
child: []
});
if (id < 2) {
this.handleArrayDepth(arrayitem.child);
}
});
};
console.log(Myarray);
The initial state of my array logs like this:
0:{
id: 1,
child: []
}
If the button is clicked twice, the output appears as follows:
0:{
id: 1,
child: [
0:{
id: 2,
child: []
},
1:{
id: 3,
child: []
}
]
}
However, what I am aiming for is the following structure:
0:{
id: 1,
child: [
0:{
id: 2,
child: [
0:{
id: 3,
child: []
}
]
}
]
}
I wish for this nesting to continue recursively/indefinitely with each click. I am currently struggling to find an efficient solution for this.