Recursive tree search in a nested object structure in JavaScript Recursive tree search in a nested object structure in JavaScript json json

Recursive tree search in a nested object structure in JavaScript


Your code is just missing a loop to inspect each child of a node in the child array. This recursive function will return the label property of a node or undefined if label not present in tree:

const search = (tree, target) => {  if (tree.id === target) {    return tree.label;  }    for (const child of tree.child) {    const found = search(child, target);        if (found) {      return found;    }  }};const tree = {"id":1,"label":"A","child":[{"id":2,"label":"B","child":[{"id":5,"label":"E","child":[]},{"id":6,"label":"F","child":[]},{"id":7,"label":"G","child":[]}]},{"id":3,"label":"C","child":[]},{"id":4,"label":"D","child":[{"id":8,"label":"H","child":[]},{"id":9,"label":"I","child":[]}]}]};console.log(search(tree, 1));console.log(search(tree, 6));console.log(search(tree, 99));