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 tagId
is 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]
}));