Last active
September 15, 2015 20:54
-
-
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.
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
| /** | |
| * 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