Skip to content

Instantly share code, notes, and snippets.

@mrwest808
Last active September 15, 2015 20:54
Show Gist options
  • Save mrwest808/275235b5efc1e1aba460 to your computer and use it in GitHub Desktop.
Save mrwest808/275235b5efc1e1aba460 to your computer and use it in GitHub Desktop.
Reduce an array of objects into an object indexed on the specified property.
/**
* Reduce an array of objects into an object indexed on the specified property.
*
* @param {array} arr
* @param {string} prop
* @return {object}
*/
function toObject(arr, prop) {
return arr.reduce((acc, obj) => (
{...acc, [obj[prop]]: obj}
), {});
}
/* Examples
===================================== */
const arrayOfObjects = [
{id: 'user1', name: 'John'},
{id: 'user2', name: 'Jane'}
];
toObject(arrayOfObjects, 'id');
/**
* Output:
* {
* user1: {
* id: 'user1',
* name: 'John'
* },
* user2: {
* id: 'user2',
* name: 'Jane'
* }
* }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment