Skip to content

Instantly share code, notes, and snippets.

@wesm87
Last active January 2, 2018 17:32
Show Gist options
  • Save wesm87/202b720caf829d6dfca35238c1d8ab12 to your computer and use it in GitHub Desktop.
Save wesm87/202b720caf829d6dfca35238c1d8ab12 to your computer and use it in GitHub Desktop.
Reduce an array of objects to a map keyed by the specified property
const recordList = [
{ id: 1, a: 'b' },
{ id: 2, foo: 'bar' },
{ id: 3, hello: 'world' },
]
/**
* Lodash FP Version
*/
import { keyBy, property } from 'lodash/fp'
const keyById = keyBy(property('id'))
const recordMap = keyById(recordList)
// => { 1: { id: 1, a: 'b' }, 2: { id: 2, foo: 'bar' }, ... }
/**
* Ramda / manual Version
*/
import { curry, prop } from 'ramda'
// keyBy :: String -> Array<Object> -> Object
export const keyBy = curry((key, collection) => {
const keyByReducer = (obj, item) => ({
...obj,
[item[key]]: item,
})
return collection.reduce(keyByReducer, {})
})
// Create a re-usable function for a specific key.
const keyById = keyBy('id')
const recordMap2 = keyById(recordList)
// Provide both arguments for single use.
const recordMap3 = keyBy('id', recordList)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment