zipObject.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var isArray = require('../lang/isArray');
  2. /**
  3. * The inverse of `_.pairs`; this method returns an object composed from arrays
  4. * of property names and values. Provide either a single two dimensional array,
  5. * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
  6. * and one of corresponding values.
  7. *
  8. * @static
  9. * @memberOf _
  10. * @alias object
  11. * @category Array
  12. * @param {Array} props The property names.
  13. * @param {Array} [values=[]] The property values.
  14. * @returns {Object} Returns the new object.
  15. * @example
  16. *
  17. * _.zipObject([['fred', 30], ['barney', 40]]);
  18. * // => { 'fred': 30, 'barney': 40 }
  19. *
  20. * _.zipObject(['fred', 'barney'], [30, 40]);
  21. * // => { 'fred': 30, 'barney': 40 }
  22. */
  23. function zipObject(props, values) {
  24. var index = -1,
  25. length = props ? props.length : 0,
  26. result = {};
  27. if (length && !values && !isArray(props[0])) {
  28. values = [];
  29. }
  30. while (++index < length) {
  31. var key = props[index];
  32. if (values) {
  33. result[key] = values[index];
  34. } else if (key) {
  35. result[key[0]] = key[1];
  36. }
  37. }
  38. return result;
  39. }
  40. module.exports = zipObject;