猿问

javascript 数组和对象遍历的问题

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

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


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

怎么实现?


烙印99
浏览 449回答 4
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不

MMTTMM

let obj = {};arr.forEach(a => obj[a['id']] = a['name']);console.log(obj);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答