UNPKG

@mightyplow/jslib

Version:

js helpers library

42 lines (32 loc) 1.33 kB
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import checkArray from '../array/_checkArray'; /** * Receives an array of objects and extracts an object with the given key as index. The key * must be a property of the array items. If the property is not found on the item, the item * is omitted. * * @memberOf object * @param {Object[]} array * @param {string} key * @param {boolean} keep - should the extracted prop be kept in the result object * @returns {*} */ var fromArray = function fromArray(array, key) { var keep = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; checkArray(array); if (!(typeof key === 'string')) { throw Error('key must be a string'); } return array.reduce(function (object) { var item = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var prop = item[key], rest = _objectWithoutProperties(item, [key]); if (!prop) { return object; } var value = item[key]; object[value] = keep ? item : rest; return object; }, {}); }; export default fromArray;