wesm87
10/18/2017 - 5:26 PM

keyBy

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)