_.fromPairs(pairs)

18

_.fromPairs(pairs)

与_.toPairs方法相反,根据key-value键值对数组生成对应的对象。

参数

pairs (Array): 键值对数组

返回值

(Object):返回一个新对象

例子

_.fromPairs([['a', 1], ['b', 2]]);
// => { 'a': 1, 'b': 2 }

源代码:

/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <https://lodash.com/license>
 */

/**
 * The inverse of `_.toPairs`; this method returns an object composed
 * from key-value `pairs`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Array
 * @param {Array} pairs The key-value pairs.
 * @returns {Object} Returns the new object.
 * @example
 *
 * _.fromPairs([['a', 1], ['b', 2]]);
 * // => { 'a': 1, 'b': 2 }
 */
//与_.toPairs方法相反,根据键值对数组生成对应的对象
function fromPairs(pairs) {
  var index = -1,//循环索引
      length = pairs ? pairs.length : 0,//键值对数组的长度
      result = {};//结果对象

  while (++index < length) {//循环并给结果对象加入属性
    var pair = pairs[index];
    result[pair[0]] = pair[1];
  }
  return result;
}

module.exports = fromPairs;

 

posted @ 2018-10-11 14:03  hahazexia  阅读(660)  评论(0)    收藏  举报