fromArray.js 841 B

123456789101112131415161718192021222324252627282930313233
  1. import checkArray from '../array/_checkArray';
  2. /**
  3. * Receives an array of objects and extracts an object with the given key as index. The key
  4. * must be a property of the array items. If the property is not found on the item, the item
  5. * is omitted.
  6. *
  7. * @memberOf object
  8. * @param {Object[]} array
  9. * @param {string} key
  10. * @param {boolean} keep - should the extracted prop be kept in the result object
  11. * @returns {*}
  12. */
  13. const fromArray = (array, key, keep = true) => {
  14. checkArray(array);
  15. if (!(typeof key === 'string')) {
  16. throw Error('key must be a string');
  17. }
  18. return array.reduce((object, item) => {
  19. const { prop, ...rest } = item;
  20. if (!prop) {
  21. return object;
  22. }
  23. object[prop] = keep ? item : rest;
  24. return object;
  25. }, {});
  26. };
  27. export default fromArray;