Convert an array of objects into a keyed object
Install
$ npm install array-to-obj
Usage
id
Default key is const arrayToObj = ; const districts = id: 1 name: 'Richmond' id: 2 name: 'Cow Hollow, Marina, Pacific Heights'; ; // {// 1: { id: 1, name: 'Richmond' },// 2: { id: 2, name: 'Cow Hollow, Marina, Pacific Heights' }// }
Pass a string as a key selector
const arrayToObj = ; const songs = title: 'Bluebird' artist: 'One Self' title: 'Sunshine' artist: 'Atmosphere'; ; // {// Bluebird: { title: 'Bluebird', artist: 'One Self' },// Sunshine: { title: 'Sunshine', artist: 'Atmosphere' }// }
Pass a function as a key selector
const arrayToObj = ; const browsers = engine: 'Blink' name: 'Chrome' engine: 'Gecko' name: 'Firefox'; ; // {// blink: { engine: 'Blink', name: 'Chrome' },// gecko: { engine: 'Gecko', name: 'Firefox' }// }
Try/catch in function selector
const arrayToObj = ;const shortid = ; const books = title: 'The Three-Body Problem' meta: upc: 9781784971571 title: 'The Dark Forest'; const converted = ;
Pass a function as a key generator
const arrayToObj = ;const shortid = ; const movies = released: '2001' title: 'Spirited Away' released: '2004' title: 'Howl\'s Moving Castle'; ;// {// qy5Tisvbu: { released: '2001', title: 'Spirited Away' },// kYzoS40SOn: { released: '2004', title: 'Howl\'s Moving Castle' }// }
API
arrayToObj(input, [options])
input
Type: array
An array of objects to convert to an object.
options
Type: Object
key
Type: string
or function
Default: 'id'
The property to use as a key. The array index is used when the property is undefined.
License
MIT © Chris Vogt