Lodash - transform method


Advertisements

Syntax

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

An alternative to _.reduce; this method transforms object to a new accumulator object which is the result of running each of its own enumerable string keyed properties thru iteratee, with each invocation potentially mutating the accumulator object. If accumulator is not provided, a new object with the same [[Prototype]] will be used. The iteratee is invoked with four arguments: (accumulator, value, key, object). Iteratee functions may exit iteration early by explicitly returning false.

Arguments

  • object (Object) − The object to iterate over.

  • [iteratee=_.identity] (Function) − The function invoked per iteration.

  • [accumulator] (*) − The custom accumulator value.

Output

  • (*) − Returns the accumulated value.

Example

var _ = require('lodash');
var array = [1, 2, 3, 4];
var transformedResult = _.transform(array, function(result, n) {   
   result.push(n *= n);
   return n % 2 == 0;
}, []);
console.log(transformedResult);

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

[ 1 ]
lodash_object.htm
Advertisements