Created
March 31, 2023 22:00
-
-
Save sergiycheck/95dbbebc416245d6ca1acfadfca98034 to your computer and use it in GitHub Desktop.
join with lookup tables on js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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