I am working on a find() function that searches for an element by tag name within a nested structure. I have attempted to iterate through all the children elements to locate the matching element.
function find(tag: string) {
let children = data.children;
for(let i = 0; i <= children.length; i++) {
if (children[i].type == 0 && children[i].tag == tag) {
return children[i];
} else {
if (children[i].children) {
children = children[i].children;
}
}
}
}
However, I have encountered two issues. Firstly, the found
variable has a different scope inside the loop and is not accessible outside it.
The children
variable in the loop body is also causing syntax errors.
Any suggestions on how to simplify this code?
let data = {
"children": [
{children: [{tag: 1, children: [{tag: 3}]}]},
]
}
I also tried the following approach:
function find(tag: string) {
let children = data.children;
let found;
return function() {
for(let i = 0; i < children.length; i++) {
if (children[i].tag == tag) {
return;
}
if (children[i].children) {
children = children[i].children;
}
}
}
}
let a = find('tag');
let result = a();
console.log(result);