Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a property of each object inside an array of objects?

I have this array as example:

array = [{id:3},{id:2},{id:4}]

I want to loop through this array of objects, and make each "id" from each object equal to its index position inside of the array, to make something like this:

array =[{id:0},{id:1},{id:2}]

Any idea of how can I do this?

Thank you all for the attention!

like image 720
Roger Peixoto Avatar asked Dec 13 '25 01:12

Roger Peixoto


1 Answers

Using forEach metohd will loop to every object in the array then to change a property value of an object to the index of the element you must pass the object and its index as the second args then equate it to the object property.

let array = [{id:3},{id:2},{id:4}] 
 array.forEach((item, index) => { 
 item.id = index 
})
like image 123
Kyle Allen Avatar answered Dec 14 '25 13:12

Kyle Allen