我有这一系列的用户。
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。
答案 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);