Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
Trying to find an object with a key in a nested array in javascript

I'm trying to pass a key to a recursive function and find and return that object with that key.

This is the array that I like to search into

const treeData = [
  {
    title: 'parent 1',
    key: '0-0',
    children: [
      {
        title: 'parent 1-0',
        key: '0-0-0',
        disabled: true,
        children: [
          {
            title: 'leafffff',
            key: '0-0-0-0',
            disableCheckbox: true,
          },
          {
            title: 'leaf',
            key: '0-0-0-1',
          },
        ],
      },
    ],
  },
];

And this is my current function

function findNode(x, key) {
    if (x.key === key)
        return x
    else if (Array.isArray(x)) {
        return x.map(item => {
            const r = findNode(item, key)
            if (r) return r
            if (item.children)
                return findNode(item.children, key)
        })
    }
}

Live example:

const treeData = [ { title: 'parent 1', key: '0-0', children: [ { title: 'parent 1-0', key: '0-0-0', disabled: true, children: [ { title: 'leafffff', key: '0-0-0-0', disableCheckbox: true, }, { title: 'leaf', key: '0-0-0-1', }, ], }, ], }, ];
function findNode(x, key) {
  if (x.key === key)
    return x
  else if (Array.isArray(x)) {
    return x.map(item => {
      const r = findNode(item, key)
      if (r) return r
      if (item.children)
        return findNode(item.children, key)
    })
  }
}

const node = findNode(treeData, '0-0-0-1')
console.log(node)

Using this function I can find the result but is not in the current format. I like to get a single object but gives me nested array with that object in the most nested child

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could iterate the array and exit early on find, either by finding the node directly or by finding it by iterating the children.

const
    find = (key, array = []) => {
        let node;
        array.some(object => node = object.key === key
            ? object
            : find(key, object.children)
        );
        return node;
    }
    data = [{ title: 'parent 1', key: '0-0', children: [{ title: 'parent 1-0', key: '0-0-0', disabled: true, children: [{ title: 'leafffff', key: '0-0-0-0', disableCheckbox: true }, { title: 'leaf', key: '0-0-0-1' }] }] }];

console.log(find('0-0', data));
console.log(find('0-0-0', data));
console.log(find('0-0-0-0', data));
console.log(find('0-0-0-1', data));
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

const treeData = [
  {
    title: 'parent 1',
    key: '0-0',
    children: [
      {
        title: 'parent 1-0',
        key: '0-0-0',
        disabled: true,
        children: [
          { title: 'leafffff', key: '0-0-0-0', disableCheckbox: true },
          { title: 'leaf', key: '0-0' },
        ],
      },
    ],
  },
];
const findNodeInTree = (tree, key) => {
  let result = null;
  tree.forEach(node => {
    if (node.key === key) {
      result = node;
    } else if (node.children) {
      result = findNodeInTree(node.children, key);
    }
  });
  return result;
}
console.log(findNodeInTree(treeData, '0-0-0-0'));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda