javascript 数组和对象遍历的问题

var arr =[{id:1,name:'name1'},{id:4,name:'name2'},{id:5,name:'name3'}];

想把 arr这个数组最后变成下面对象的格式

obj ={1:'name1',4:'name2',5:'name3'};

怎么实现?

阅读 2.8k
4 个回答
var arr =[{id:1,name:'name1'},{id:4,name:'name2'},{id:5,name:'name3'}]
var obj = {};
for(var i in arr){
    var d = arr[i].name;
    var e = arr[i].id;
    obj[e] = d;    
}

low不

let obj = {};
arr.forEach(a => obj[a['id']] = a['name']);

console.log(obj);
var arr =[{id:1,name:'name1'},{id:4,name:'name2'},{id:5,name:'name3'}];
    var obj=arr.reduce(function(a,b){
        return a[b.id]=b.name,a;
    },{});
    console.log(obj);
var arr =[{id:1,name:'name1'},{id:4,name:'name2'},{id:5,name:'name3'}]

var obj = arr.reduce((ret, item) => (ret[item.id] = item.name, ret), {})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题