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

133
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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