-1

I have this array of users.

users = [
 {id:"1", name:"Akash", email: "[email protected]"},
 {id:"2", name:"Akshay", email: "[email protected]"}
]

I want to transform this array into an object like this.

users = {
 "1" : {id:"1", name:"Akash", email: "[email protected]"},
 "2" : {id:"2", name:"Akshay", email: "[email protected]"}
}

I am using node js.

0

3 Answers 3

0

You can use Array​.prototype​.reduce()

let users = [
 {id:"1", name:"Akash", email: "[email protected]"},
 {id:"2", name:"Akshay", email: "[email protected]"}
]

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)

Sign up to request clarification or add additional context in comments.

Comments

0

Use array.reduce

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

Comments

0

Please check the below code:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.