如何在javascript中重命名数组中对象的属性?

时间:2017-07-07 09:01:51

标签: javascript jquery

我有这个javascript对象:

var arr = [{id:'124',name:'qqq'}, 
           {id:'589',name:'www'}, 
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}]

我需要将arr1中name的属性重命名为title

var arr = [{id:'124',title:'qqq'}, 
           {id:'589',title:'www'}, 
           {id:'45',title:'eee'},
           {id:'567',title:'rrr'}]

在Javascript中实现它的优雅方法是什么?

5 个答案:

答案 0 :(得分:5)

使用delete从对象中删除属性。 使用obj['newProperty']newProperty分配给对象。



var arr = [{id:'124',name:'qqq'}, 
           {id:'589',name:'www'}, 
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}];
           
arr.forEach( function(data) {
  data['title'] = data['name'];
  delete data['name'];
});

console.log(arr);




答案 1 :(得分:2)

无法更改属性名称,但添加新属性并删除旧属性,我也从某处获取代码不记得确切来源

function changeKey(originalKey, newKey, arr)
{
  var newArr = [];
  for(var i = 0; i < arr.length; i++)
  {
    var obj = arr[i];
    obj[newKey] = obj[originalKey];
    delete(obj[originalKey]);
    newArr.push(obj);
  }
  return newArr;
}

答案 2 :(得分:0)

使用map

&#13;
&#13;
var arr = [{
    id: '124',
    name: 'qqq'
  },
  {
    id: '589',
    name: 'www'
  },
  {
    id: '45',
    name: 'eee'
  },
  {
    id: '567',
    name: 'rrr'
  }
]

arr = arr.map((e) => {
  return {
    id: e.id,
    title: e.name
  }
});

console.log(arr);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

arr.map(e => { return { id: e.id, title: e.name }});

答案 4 :(得分:0)

以下是删除键和值并分配给新键的方法:

var arr = [{id:'124',name:'qqq'}, 
           {id:'589',name:'www'}, 
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}]
           
arr.forEach(function(o) {
    Object.defineProperty(o, 'title',
        Object.getOwnPropertyDescriptor(o, 'name'));
    delete o['name'];
});           
console.log(arr);