codecat
codecat

Reputation: 145

How to add key id to array of objects in javascript

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 }
]

Upvotes: 0

Views: 1922

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

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);

Upvotes: 0

Ashish Mishra
Ashish Mishra

Reputation: 422

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);

Upvotes: 1

Related Questions