I have a dilemma of which case is more efficient.
I have a javascript array with this structure
elements =
[ { id: 'uuid', children: [] }
, { id: 'uuid', children: [] }
, { id: 'uuid', children:
[ { id: 'uuid', children: [] }
, { id: 'uuid', children:
[ { id: 'uuid', children: [] }
, { id: 'uuid', children: [] }
]
}
, { id: 'uuid', children: [] }
]
}
]
To find a specific object, I have two ways of working, one is to iterate each element until I find it and the other is to convert it to string and if the id exists in the children, I enter the node
function findElementById(id_, elements){
for (el of elements){
if(el.id == id_) return el
if(JSON.stringify(el.children).includes(id_)) return findElementById(id, el.children)
}
}
function findElementById(id_, elements){
for (el of elements){
if(el.id == id_) return el
if(el.children.length > 0) result = findElementById(id, el.children)
if (result) return result
}
}
It's efficient to convert to string to avoid entering nodes that will not return anything or in cases where the object is very large, converting to string uses a lot of resources.