Discussion

Make a mapping object from an array of objects using Reduce function in Javascript

Sometimes, we face some usecases to make a mapping object from an array of object.

For example, we have a Users array, we need to find a user by tagId. Here tagIdis supposed to be unique. Generally, we may try to use array.find() function to find the object with tagId.

But using array.reduce()function in Javascript, we can make it simple.

const users = await User.find();
// users = [{
//   id: string,
//   tagId: string,
//   name: string
// }]

const usernamesByTagId = users.reduce(
   (lookup, user) => ({
      ...lookup,
      [user.tagId]: user.name || '',
   }),
   {},
 );

// this mapping is used below
const result = someArrayData.mapping((item) => ({
  ...item,
  name: usernamesByTagId[item.tagId]
}));

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *