0

I have array of objects, which need to add id in javascript.

function addKey(obj){
 return obj.map(e=>({...e, id:index})
}

var obj=[
  {name: "s1"},
  {name: "s2"}
]


Expected Output

[
  {name: "s1", id:0 },
  {name: "s2", id:1 }
]

2 Answers 2

1

using object.assign u can add key

 var obj = [{
     name: 's1'
 }, {
  name: 's2'
  }];

 var result = obj.map(function(el,index) {
 var o = Object.assign({}, el);
 o.id = index;
 return o;
})

console.log(result);
Sign up to request clarification or add additional context in comments.

1 Comment

Why use Object.assign when OP was already using spread syntax? e.g. { ...e, id: index }
0

You can add an id property by adding the index of an Array.prototype.map callback.

const
  obj = [
    { name: "s1" },
    { name: "s2" }
  ],
  offset = 2;

console.log(obj.map((item, id) => ({ ...item, id: id + offset })));

If you want to modify the object in-place (without polluting memory), you can try the following:

const
  obj = [
    { name: "s1" },
    { name: "s2" }
  ],
  offset = 2;

obj.forEach((item, index) => item.id = index + offset)

console.log(obj);

2 Comments

how bout when i want to start the count or the id from a static number like 2
@d'reaper I added an offset to show how to add it.

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.