3

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!

3 Answers 3

4

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 
})
Sign up to request clarification or add additional context in comments.

2 Comments

Even though this may answer the question, there is no explanation of your code. Please update your answer to provide an explanation of what you are doing. Thanks!
@MiroslavGlamuzina I'm sorry. I'm still learning just started answering questions. Thanks for your comment anyway! Will edit my answer.
4

Simple map would work:

const array = [{id:3},{id:2},{id:4}];
const newArray = array.map((e, i) => ({ id: i }));
console.log(newArray);
.as-console-wrapper { max-height: 100% !important; top: auto; }

If you want to keep all other properties the same (if you have multiple properties):

const array = [{id:3, name: "A"},{id:2, name: "B"},{id:4, name: "C"}];
const newArray = array.map((e, i) => ({ ...e, id: i }));
console.log(newArray);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Comments

1

For completeness, you can loop over an array with a simple for loop:

for (var i = 0; i < array.length; i++) {
  array[i].id = i;
}

2 Comments

When I try this approach, it gives me an "Cannot set property 'id' of undefined" :(
Then your array might have holes or you are iterating over it incorrectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.