transform source npm

_.transform(object, [iteratee=_.identity], [accumulator])

_.reduce 的代替方法。 这个方法会改变对象为一个新的 accumulator 对象,来自每一次经 iteratee 处理自身可枚举对象的结果。 每次调用可能会改变 accumulator 对象。 iteratee 会传入4个对象:(accumulator, value, key, object)。 如果返回 false,iteratee 会提前退出。

参数

  1. object (Array|Object)

    要遍历的对象

  2. [iteratee=_.identity] (Function)

    这个函数会处理每一个元素

  3. [accumulator] (*)

    定制叠加的值

返回值 (*)

返回叠加后的值

示例

_.transform([2, 3, 4], function(result, n) {
  result.push(n *= n);
  return n % 2 == 0;
}, []);
// => [4, 9]

_.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  (result[value] || (result[value] = [])).push(key);
}, {});
// => { '1': ['a', 'c'], '2': ['b'] }