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

358
Visualizações
What is the best way to find index of an item inside an array and that array is inside another away

I was wondering what is the best way to find the index of an item that is located inside an array, and that array is located inside another array.

This is the kind of data I have:

const list = [
  {
    id: 1,
    items: [
      {
        name: "milk",
        id: 99
      },

      { name: "water", id: 33 }
    ]
  },
  {
    id: 4,
    items: [
      {
        name: "oranges",
        id: 22
      },

      { name: "patatoes", id: 13 }
    ]
  }
];

Lets say that I want to know the index of the item with the name "milk", I already know the id of the parent object (1), and I also know the id of the item(99).

My goal is to change the name of the item from "milk" to "cheese", My first idea was to do it like this:

const firstObjectIndex = arr.findIndex(el => el.id === 1) 
if(firstObjectIndex !== -1){
const itemIndex = arr[firstObjectIndex].items.findIndex(item => item.id === 99)

 if(itemIndex !== -1){
  // this is where I change the name to cheese
  arr[firstObjectIndex].items[itemIndex].name = 'Cheese'
 }
}

The method I used above does the job, but I am wondering if there is a better way to do this in JavaScript? Any help would be greatly appreciated

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You don't really need the index, but the object itself. Therefore, use Array#find. This allows both of the searches to be easily combined into one statement with the optional chaining operator.

const list=[{id:1,items:[{name:"milk",id:99},{name:"water",id:33}]},{id:4,items:[{name:"oranges",id:22},{name:"patatoes",id:13}]}];
let obj = list.find(x => x.id === 1)?.items.find(y => y.name === 'milk');
if(obj) obj.name = 'Cheese';
console.log(list);

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