Last active
July 15, 2020 21:07
-
-
Save C5H8NNaO4/67c05bbf716b3f4f24494c3419ec6757 to your computer and use it in GitHub Desktop.
Left join
This file contains 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
//Closed question on Stackoverflow | |
//https://stackoverflow.com/questions/62923537/create-new-object-using-two-objects-that-share-a-prop# | |
users = [ | |
{userId: 1, name: "John", favoriteFruit: "Apple"}, | |
{userId: 2, name: "Jerry", favoriteFruit: "Pear"}, | |
{userId: 3, name: "Linda", favoriteFruit: "Peach"}, | |
{userId: 4, name: "Cruz", favoriteFruit: "Banana"}, | |
]; | |
cars = [ | |
{userId: 1, carModel: "GT200", color: "Blue"}, | |
{userId: 1, carModel: "GT300", color: "Green"}, | |
{userId: 2, carModel: "F200", color: "Black"}, | |
{userId: 4, carModel: "F1200", color: "White"}, | |
{userId: 4, carModel: "RT600", color: "Pink"}, | |
{userId: 3, carModel: "GT200", color: "Yellow"}, | |
]; | |
function leftJoin(l, r, on) { | |
const lkp = r.reduce((acc, cur) => { | |
acc[cur[on]] = cur; | |
return acc; | |
}, {}) | |
return l.map((e) => { | |
const from = lkp[e[on]]; | |
return {...e, ...from} | |
}) | |
} | |
const joined = leftJoin(cars, users, 'userId'); | |
console.log (joined) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment