Skip to content

Instantly share code, notes, and snippets.

@ourmaninamsterdam
Created October 14, 2019 17:33
Show Gist options
  • Save ourmaninamsterdam/ba27c460a8fd5cff761cdfcce191b4dc to your computer and use it in GitHub Desktop.
Save ourmaninamsterdam/ba27c460a8fd5cff761cdfcce191b4dc to your computer and use it in GitHub Desktop.
Maps array of objets to a key value object using key provided
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