Guest User

Untitled

a guest
Oct 19th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.62 KB | None | 0 0
  1. const recordList = [
  2. { id: 1, a: 'b' },
  3. { id: 2, foo: 'bar' },
  4. { id: 3, hello: 'world' },
  5. ]
  6.  
  7. /**
  8. * Lodash Version
  9. */
  10. import { property, keyBy } from 'lodash/fp'
  11.  
  12. const keyById = keyBy(property('id'))
  13.  
  14. const recordMap = keyById(recordList)
  15.  
  16. /**
  17. * Manual Version
  18. */
  19. export function keyBy(key: string) {
  20. const keyByReducer = (map, item) => ({
  21. ...map,
  22. [item[key]]: item,
  23. })
  24.  
  25. return (collection) => collection.reduce(keyByReducer, {})
  26. }
  27.  
  28. // Create re-usable function for a specific key
  29. const keyById = keyBy('id')
  30. const recordMap2 = keyById(recordList)
  31.  
  32. // Chain method calls
  33. const recordMap3 = keyBy('id')(recordList)
Add Comment
Please, Sign In to add comment