简体   繁体   中英

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

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

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

 const obj = [ { name: "s1" }, { name: "s2" } ] console.log(obj.map((item, id) => ({ ...item, id })));

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

 const obj = [ { name: "s1" }, { name: "s2" } ] obj.forEach((item, index) => item.id = index) console.log(obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM