mi compañero y yo nos hemos estado rompiendo la cabeza con esto. tenemos que crear un árbol, que obviamente tiene "hijos" debajo.
todo lo que necesitamos ahora es recorrer un objeto para encontrar un cierto valor, si ese valor no está en ese cierto objeto, entonces vaya a su propiedad secundaria y mire allí.
básicamente, lo que estoy preguntando es, ¿cómo puede recorrer objetos anidados hasta que se encuentre un cierto valor?
agradecería mucho la perspectiva de un codificador más experimentado sobre esto.
/// this is how one parent with a child tree looks like right now, essentially if we presume that the child has another child in the children property, how would we loop into that? and maybe if that child also has a child, so on and so on... Tree { value: 'Parent', children: [ Tree { value: 'Child', children: [] } ] }Puede usar la función recursiva para recorrer objetos:
const Tree = { value: 'Parent', children: [ { value: 'Child1', children: [ ] }, { value: 'Child2', children: [ { value: 'Child2.1', children: [ { value: 'Child2.1.1', children: [ ] }, { value: 'Child2.1.2', children: [ ] }, ] }, ] }, ] } function findValue(obj, value) { if (obj.value == value) return obj; let ret = null; for(let i = 0; i < obj.children.length; i++) { ret = findValue(obj.children[i], value); if (ret) break; } return ret; } console.log("Child1", findValue(Tree, "Child1")); console.log("Child2.1", findValue(Tree, "Child2.1")); console.log("Child3", findValue(Tree, "Child3"));Puedes probar esta sencilla solución:
const myTree = { value: 'Parent', children: [ { value: 'Child1', children: [] }, { value: 'Child2' } ] } const isValueInTree = (tree, findValue) => { if (tree.value === findValue) return true; if (tree.children && tree.children.length !== 0) { for (const branch of tree.children) { const valuePresents = isValueInTree(branch, findValue); if (valuePresents) return true; } } return false; } console.log(isValueInTree(myTree, 'Child2')); console.log(isValueInTree(myTree, 'Child')); console.log(isValueInTree(myTree, 'Child1'));