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

153
Vistas
get id by value in hierarcial data with js

I have hierarcial data as tree array:

var myData = [
    {
      id: 0,
      title:"Item 1"
    }, {
      id: 1,
      title:"Item 2",
      subs: [
        {
          id: 10,
          title:"Item 2-1"
        }, {
          id: 11,
          title:"Item 2-2"
        }, {
          id: 12,
          title:"Item 2-3"
        }
      ]
    }, {
      id: 2,
      title:"Item 3"
    },
    // more data here
];

I need to get id by title in this array. I try to use this function:

console.log(myData.findIndex(item=>item.title==="Item 3"))

But it works bad for "Item 2-2". How should I solve this problem?

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

0

I made this simple findId method in order to find the title and returns the id or undefined as result made for your data array structure.

This will work fine, assuming each title is unique in the array.
Otherwise only the first will be found.

Take a look at the following

var myData = [{
    id: 0,
    title: "Item 1"
  }, {
    id: 1,
    title: "Item 2",
    subs: [{
      id: 10,
      title: "Item 2-1"
    }, {
      id: 11,
      title: "Item 2-2"
    }, {
      id: 12,
      title: "Item 2-3"
    }]
  }, {
    id: 2,
    title: "Item 3"
  },
  // more data here
];

function findId(title) {
  // Item with the equal title or with a children with an equal title
  const item = myData.filter(d => (d.title === title || d?.subs?.filter(s => s.title === title).length > 0))[0];

  if (item) {
    // Check if is the main element or is one of the subs (with ternary operator)
    const id = item.title === title ? item.id : item?.subs?.filter(s => s.title === title)[0].id;

    // Return the id
    return id;
  }
  // Return undefined if not found
  return undefined;
}


console.log("Id: ", findId("Item 3"));
console.log("Id: ", findId("Item 2-3"));
console.log("Id: ", findId("Item 2-1"));
console.log("Id: ", findId("Not Found"));

The last one returns undefined as intended, since the title is not included in the array.

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