0

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

2 Answers 2

2

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 },
  }),
  {}
);
Sign up to request clarification or add additional context in comments.

8 Comments

I like { phoneNumber, ...rest }. I didn't know the rest operator also works with objects.
thanks, he needs that as the objects inside the array also contains other properties other than name
{"03005359279": {"other": "anything","name": "ZOHAIB"}, "03212744193": {"other":"other thing", "name": "Muhammad Zohaib"}}
@Oussama thanks dear
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
|
2

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

2 Comments

Just a little tunning for reduce variant customers.reduce((acc, {phoneNumber, name}) => ({...acc, [phoneNumber]: { name } }), {});
@Ffire Yes, but I don't want to copy the other answer and IMO the reducer in the other answer is better than mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.