阅读(563) (0)

Lodash _.transform

2021-09-23 09:28:27 更新

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

_.reduce的替代方法;此方法将转换object对象为一个新的accumulator对象,结果来自iteratee处理自身可枚举的属性。 每次调用可能会改变 accumulator 对象。如果不提供accumulator,将使用与[[Prototype]]相同的新对象。iteratee调用4个参数:(accumulator, value, key, object)。如果返回 false,iteratee 会提前退出。

添加版本

1.3.0

参数

  1. object (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'] }