Lodash _.transform() Method
Last Updated :
31 Oct, 2023
Lodash _.transform() method is an alternative to the _.reduce() method transforms an object to a new accumulator object which is the result of running each of its own enumerable string keyed properties through iteratee with each invocation potentially mutating the accumulator object. A new object with the same prototype will be used if an accumulator is not provided.
Syntax:
_.transform(object, iteratee, accumulator);
Parameters:
- object: It holds the object to iterate over.
- iteratee: It is the function that the method invoked per iteration for every element.
- accumulator: It holds the custom accumulator value.
Return Value:
This method returns the accumulated value.
Example 1: In this example, we are transforming the given array by the use of the lodash _.transform() method.
javascript
const _ = require( "lodash" );
let object = [12, 13, 14];
let st_elem = _.transform(object,
function (result, n) {
result.push(n *= n);
return n % 2 == 0;
}, []);
console.log(st_elem);
|
Output:
144, 169
Example 2: In this example, we are transforming the given array by the use of the lodash _.transform() method.
javascript
const _ = require( "lodash" );
let object = { 'p' : 3, 'q' : 6, 'r' : 3 };
let st_elem = _.transform(object,
function (result, value, key) {
(result[value] || (result[value] = [])).push(key);
}, {});
console.log(st_elem);
|
Output:
{ '3': ['p', 'r'], '6': ['q'] }
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...