Skip to content

Instantly share code, notes, and snippets.

@sergiycheck
Created March 31, 2023 22:00
Show Gist options
  • Save sergiycheck/95dbbebc416245d6ca1acfadfca98034 to your computer and use it in GitHub Desktop.
Save sergiycheck/95dbbebc416245d6ca1acfadfca98034 to your computer and use it in GitHub Desktop.
join with lookup tables on js
const messages = [
{
id: 1,
text: 'text 1',
userId: 1
},
{
id: 2,
text: 'text 2',
userId: 1
},
{
id: 3,
text: 'text 2',
userId: 2
},
{
id: 4,
text: 'text 2',
userId: 3
},
];
const users = [
{ id: 1, name: 'user 1' },
{ id: 2, name: 'user 2' },
{ id: 3, name: 'user 3' },
];
const usersLookup = Object.fromEntries(
users.map( (u) => ( [ [u.id], u ] ) )
)
const messagesByUserId = messages.reduce((prev, curr) => {
if(curr.userId in prev) {
prev[curr.userId] =
[
...prev[curr.userId],
{
...curr,
user: usersLookup[curr.userId]
}
]
}else {
prev[curr.userId] = [
{
...curr,
user: usersLookup[curr.userId]
}
]
}
return prev;
}, {});
console.dir(messagesByUserId, { depth: null })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment