【问题标题】:How to add key id to array of objects in javascript如何将密钥ID添加到javascript中的对象数组
【发布时间】:2020-09-30 13:09:32
【问题描述】:

我有一个对象数组,需要在javascript中添加id

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

【问题讨论】:

    标签: javascript arrays loops object


    【解决方案1】:

    使用object.assign你可以添加键

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

    【讨论】:

    • 当 OP 已经在使用扩展语法时,为什么还要使用 Object.assign?例如{ ...e, id: index }
    【解决方案2】:

    您可以通过添加Array.prototype.map 回调的索引来添加id 属性。

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

    如果要就地修改对象(不污染内存),可以尝试以下方法:

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

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      相关资源
      最近更新 更多