Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert Array into object

I wanted to create a customer’s dictionary using reduce function, I am doing it using forEach

const customers = 
  [ { name: 'ZOHAIB', phoneNumber: '0300xxxxx', other: 'anything'     } 
  , { name: 'Zain',   phoneNumber: '0321xxxxx', other: 'other things' } 
  ] 

let customersDictionary = {};
customers.forEach(customer => {
  customersDictionary = {
      ...customersDictionary,
      [ customer.phoneNumber ]: {name: customer.name},
      };

I wanted the same output but using reduce method.

customersDictionary = 
  { "0300xxxxx": {"name": "ZOHAIB"}
  , "0321xxxxx": {"name": "Zain"}
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need reduce. It’s a one-liner with Array.prototype.map and Object.fromEntries:

Object.fromEntries(customers.map(c => [c.phoneNumber, { name: c.name }]));

The variant using reduce:

customers.reduce((acc, c) => {
  acc[c.phoneNumber] = { name: c.name };
  return acc;
}, {});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading