Created
October 14, 2019 17:33
-
-
Save ourmaninamsterdam/ba27c460a8fd5cff761cdfcce191b4dc to your computer and use it in GitHub Desktop.
Maps array of objets to a key value object using key provided
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 mapKeys = (collection, rootKey) => { | |
const obj = {}; | |
collection.forEach(item => { | |
obj[item[rootKey]] = item; | |
}); | |
return obj; | |
}; | |
const justins = [{id: 1, name: 'Justin Bieber'},{id: 2, name: 'Justin Timberlake'},{id: 3, name: 'Justin Time'}]; | |
mapKeys(justins, 'id'); | |
// { | |
// 1: {id: 1, name: 'Justin Bieber'}, | |
// 2: {id: 2, name: 'Justin Timberlake'}, | |
// 3: {id: 3, name: 'Justin Time'} | |
//} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment