_.keyBy

❗️ Lodash onlyCreates an object composed of keys generated from the results of running each element of collection thru iteratee.

  1. // Lodash
  2. console.log(_.keyBy(['a', 'b', 'c']))
  3. // output: { a: 'a', b: 'b', c: 'c' }
  4. console.log(_.keyBy([{ id: 'a1', title: 'abc' }, { id: 'b2', title: 'def' }], 'id')
  5. // output: { a1: { id: 'a1', title: 'abc' }, b2: { id: 'b2', title: 'def' } }
  6. console.log(_.keyBy({ data: { id: 'a1', title: 'abc' }}, 'id')
  7. // output: { a1: { id: 'a1', title: 'abc' }}
  8.  
  9. // keyBy for array only
  10. const keyBy = (array, key) => (array || []).reduce((r, x) => ({ ...r, [key ? x[key] : x]: x }), {});
  11.  
  12. // Native
  13. console.log(keyBy(['a', 'b', 'c']))
  14. // output: { a: 'a', b: 'b', c: 'c' }
  15. console.log(keyBy([{ id: 'a1', title: 'abc' }, { id: 'b2', title: 'def' }], 'id')
  16. // output: { a1: { id: 'a1', title: 'abc' }, b2: { id: 'b2', title: 'def' } }
  17. console.log(keyBy(Object.values({ data: { id: 'a1', title: 'abc' }}), 'id')
  18. // output: { a1: { id: 'a1', title: 'abc' }}
  19.  
  20. // keyBy for array and object
  21. const collectionKeyBy = (collection, key) => {
  22. const c = collection || {};
  23. return c.isArray() ? keyBy(c, key) : Object.values(keyBy(c, key));
  24. }

Browser Support for Array.prototype.reduce()

ChromeEdgeFirefoxIEOperaSafari
12.0 ✔3.0 ✔9.0 ✔10.5 ✔4.0 ✔