Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda