Skip to content

Instantly share code, notes, and snippets.

@lcaballero
Last active August 29, 2015 14:07
Show Gist options
  • Save lcaballero/8cc9b9dd0ec483d2e7ec to your computer and use it in GitHub Desktop.
Save lcaballero/8cc9b9dd0ec483d2e7ec to your computer and use it in GitHub Desktop.
A lodash mixin that maps an array of items to a map where.
_.mixin
###
Turns an array of values into an associated object where the keys are
properties found on items of the array. For instance, turning a list of
users into a map of IDs to the Person.
Examples:
# Simple/typical usage
lookup = _.toLookup(items, 'property')
# Full signature usage
lookup = _.toLookup(items,
(a) -> a.id
, (k) -> k.doubled)
@arr { Array } - A list of objects from which to create a map.
@keyFn { Function | String } - A function that provides the value to use
as a key. If this function provides the same key for more than one object
in the array, the later value in the array will 'win' and be the value
associated with that key.
Optionally, the key can be a string, and the operation will proceed in
a 'pluck' like style. This would look something like this:
_.toLookup(items, "id") which would produce a map with the 'id' of the
item as a key and then item itself as the value.
@toItem { Function } - Optional. A function that can be provided to produce
the value for the key. This could be derived from the item, etc. If
not provided it will default to _.identity.
###
toLookup : (arr, keyFn, toItem) ->
toKey =
if _.isString(keyFn)
then (b) -> b[keyFn]
else keyFn
toItem =
if toItem
then toItem
else _.identity
_.reduce(arr, (acc, a) ->
acc[toKey(a)] = toItem(a)
acc
, {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment