Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!