Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const recordList = [
- { id: 1, a: 'b' },
- { id: 2, foo: 'bar' },
- { id: 3, hello: 'world' },
- ]
- /**
- * Lodash Version
- */
- import { property, keyBy } from 'lodash/fp'
- const keyById = keyBy(property('id'))
- const recordMap = keyById(recordList)
- /**
- * Manual Version
- */
- export function keyBy(key: string) {
- const keyByReducer = (map, item) => ({
- ...map,
- [item[key]]: item,
- })
- return (collection) => collection.reduce(keyByReducer, {})
- }
- // Create re-usable function for a specific key
- const keyById = keyBy('id')
- const recordMap2 = keyById(recordList)
- // Chain method calls
- const recordMap3 = keyBy('id')(recordList)
Add Comment
Please, Sign In to add comment