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

139
Visualizações
how to loop through array (array of objects) starting at a specific index to the last and alter properties in the object in Javascript?
let library = []; //this stores each object 

Each object has a property called' id' where a number is stored, this represents the index of the object in the library array. Basically when an object is deleted from the library I want to get all the objects in the array that come after the deleted object and minus 1 from the id property.

function updateId(index) {
  for (let i = index; i <= library.length; i++) {
    library[i].id - 1;
  }
}

So far I have this function where the argument index is the position in the array where the object was deleted. I am getting a reference error with that last line of code

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

0

Instead of i <= library.length try i < library.length.

Currently that line is saying "continue this for loop so long as i is less than or equal to the length" ... but remember, i (ie. indices) are zero-based, while lengths aren't. This means that you'll actually loop past where you want.

about 4 years ago · Juan Pablo Isaza Relatório

0

Note this is just one of many ways to solve this! You're almost there. There are a few things that your code needs:

  • to have access to the 'library' inside of your function, you should pass it into the function. Functions should only operate on variables that they received as arguments.
  • your for loop, should go on if i is SMALLER THAN not SMALLER EQUAL to the length
  • if you're changing the 'library' in a function, you need to return it, and overwrite the original.

function updateId(library, startingAtIndex) {
      for (let i = startingAtIndex; i < library.length; i++) {
        library[i].id -= 1;
      }
      return library
 }
 
things = [{name:'a', id:1},{name:'c', id:3},{name:'d', id:4}]
things = updateId(things, 1)
console.log(things)

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