i have been trying to create a tree structure in JavaScript. However, when I use the add_child function to add a child to an item in the elements array, it adds the child to all items in the elements array and their children, creating an infinite loop.
I am unsure why this is happening.
let divBase = {
Name: "",
Type: "div",
children: [],
open: false
};
let elements = [];
let elementCounter = 0;
function add_child(parentName, childName) {
let parent = findItem(parentName)
let child = removeItem(childName)
console.log(parent)
console.log(child)
if (child != null) {
parent.children.push(child)
console.log(parent)
console.log(child)
return true
}
return false
}
// more functions and code...
if i print the elements array it is like this
(5) [{…}, {…}, {…}, {…}, {…}]
0 : {Name: 'Div 0', Type: 'div', children: Array(1), backgroundColor: '#2ecc71', width: 200, …}
1 : {Name: 'Div 1', Type: 'div', children: Array(1), backgroundColor: '#2ecc71', width: 200, …}
2 : {Name: 'Div 2', Type: 'div', children:
> Array(1), backgroundColor: '#2ecc71', width: 200, …}
3 : {Name: 'Div 3', Type: 'div', children: Array(1), backgroundColor: '#2ecc71',
> width: 200, …}
4 : {Name: 'Div 5', Type: 'div', children: Array(1), backgroundColor: '#2ecc71', width: 200, …} length : 5
thanks