Home > Net >  How to convert Array into object
How to convert Array into object

Time:12-15

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"}
}

CodePudding user response:

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;
}, {});

CodePudding user response:

This should work

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

const customersDictionary = customers.reduce(
  (acc, { phoneNumber, name }) => ({
    ...acc,
    [phoneNumber]: { name },
  }),
  {}
);
  • Related