我想将对象数组映射到js中的对象对象

时间:2019-05-07 11:16:01

标签: arrays reactjs object mapping

我有这一系列的用户。

users = [
 {id:"1", name:"Akash", email: "xyz@gmail.com"},
 {id:"2", name:"Akshay", email: "xyz2@gmail.com"}
]

我想将此数组转换成这样的对象。

users = {
 "1" : {id:"1", name:"Akash", email: "xyz@gmail.com"},
 "2" : {id:"2", name:"Akshay", email: "xyz2@gmail.com"}
}

我正在使用节点js。

3 个答案:

答案 0 :(得分:0)

使用array.reduce

users.reduce((obj, item) => {
 obj[item.id] = item
 return obj
}, {})

答案 1 :(得分:0)

您可以使用Array​.prototype​.reduce()

let users = [
 {id:"1", name:"Akash", email: "xyz@gmail.com"},
 {id:"2", name:"Akshay", email: "xyz2@gmail.com"}
]

let result=users.reduce((o,a)=>{

o[`${a.id}`]=a
return o;

},{})

console.log(result)

// or if you are looking to convert your array into object


let data=Object.assign({}, users);
console.log(data)

答案 2 :(得分:0)

请检查以下代码:

let users = [
 {id:"1", name:"Akash", email: "xyz@gmail.com"},
 {id:"2", name:"Akshay", email: "xyz2@gmail.com"}
].map(d => {
  return {[d.id]:d};}).reduce((a,b) => {return {...a,...b};});
console.log(users);