Created
February 26, 2018 13:21
-
-
Save wiyoe/843ceffec5e98519e88534bfb29c064d to your computer and use it in GitHub Desktop.
Javascript array to Object with Key
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 peopleArray = [ | |
| { id: 123, name: "dave", age: 23 }, | |
| { id: 456, name: "chris", age: 23 }, | |
| { id: 789, name: "bob", age: 23 }, | |
| { id: 101, name: "tom", age: 23 }, | |
| { id: 102, name: "tim", age: 23 } | |
| ]; | |
| const arrayToObject = (array, keyField) => | |
| array.reduce((obj, item) => { | |
| obj[item[keyField]] = item | |
| return obj | |
| }, {}); | |
| const peopleObject = arrayToObject(peopleArray, "id"); | |
| console.log(peopleObject[789]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment