-4

I've a data like this.

const arr = [
  {name:'john'},
  {name:'jeff'},
  {name:'bob'},
  {name:'peter'},
]

arr.forEach((v,i,a)=>{
  console.log(v)
})

And I want to transfer to

arr = [{id:1,name:john},{id:2,name:jeff},{id:3,name:bob},{id:4,name:peter}]

I want to add id to every object in array.

How to solves this, Thank you.

1
  • Have you looked at the documentation of forEach? Commented Oct 25, 2022 at 17:43

2 Answers 2

1

const arr = [
  {name:'john'},
  {name:'jeff'},
  {name:'bob'},
  {name:'peter'},
]

arr.forEach((v,i,a)=>{
  v.id = i + 1
})

console.log(arr)

Sign up to request clarification or add additional context in comments.

Comments

1

Try this :

const arr = [
  {name:'john'},
  {name:'jeff'},
  {name:'bob'},
  {name:'peter'},
];

const res = arr.map((obj, index) => {
   return {
     ...obj,
     id: index + 1
   }
});

console.log(res);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.