An alternative to reduce that transforms objects to new accumulator objects through iterative processing
npx @tessl/cli install tessl/npm-lodash--transform@4.6.00
# Lodash Transform
1
2
Lodash Transform provides an alternative to reduce that transforms objects to new accumulator objects through iterative processing. It iterates over object properties or array elements, allowing for flexible accumulation and transformation patterns with automatic accumulator initialization based on input type.
3
4
## Package Information
5
6
- **Package Name**: lodash
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash`
10
11
## Core Imports
12
13
```javascript
14
import _ from "lodash";
15
// Use: _.transform(...)
16
```
17
18
ES6 with destructuring:
19
20
```javascript
21
import _ from "lodash";
22
const { transform } = _;
23
```
24
25
CommonJS:
26
27
```javascript
28
const _ = require("lodash");
29
// Use: _.transform(...) or const { transform } = _;
30
```
31
32
## Basic Usage
33
34
```javascript
35
import _ from "lodash";
36
const { transform } = _;
37
38
// Transform array to new structure
39
const numbers = transform([2, 3, 4], function(result, n) {
40
result.push(n * n);
41
return n % 2 == 0; // Exit early when even number found
42
}, []);
43
// => [4, 9]
44
45
// Transform object to grouped structure
46
const users = { 'a': 1, 'b': 2, 'c': 1 };
47
const grouped = transform(users, function(result, value, key) {
48
(result[value] || (result[value] = [])).push(key);
49
}, {});
50
// => { '1': ['a', 'c'], '2': ['b'] }
51
```
52
53
## Architecture
54
55
The `transform` function implements several key design patterns that make it flexible and powerful:
56
57
- **Iteratee Pattern**: Uses lodash's internal `getIteratee` function to normalize the iteratee parameter, allowing for function shorthand, property paths, and object matching patterns
58
- **Automatic Accumulator Initialization**: When no accumulator is provided, intelligently creates one based on the input type, preserving constructors and prototype chains
59
- **Unified Array/Object Processing**: Internally uses either `arrayEach` or `baseForOwn` to handle both arrays and objects with the same interface
60
- **Early Exit Support**: The iteratee can return `false` to stop iteration early, providing performance benefits for search operations
61
- **Mutation-Safe Design**: While the accumulator can be mutated within the iteratee, the original object remains unchanged
62
63
## Capabilities
64
65
### Object Transformation
66
67
An alternative to reduce that transforms objects to new accumulator objects through iterative processing.
68
69
```javascript { .api }
70
/**
71
* An alternative to _.reduce; this method transforms object to a new
72
* accumulator object which is the result of running each of its own enumerable
73
* properties through iteratee, with each invocation potentially mutating
74
* the accumulator object. The iteratee is invoked with four arguments:
75
* (accumulator, value, key, object). Iteratee functions may exit iteration
76
* early by explicitly returning false.
77
*
78
* @param {Array|Object} object The object to iterate over.
79
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
80
* @param {*} [accumulator] The custom accumulator value.
81
* @returns {*} Returns the accumulated value.
82
*/
83
function transform(object, iteratee, accumulator);
84
```
85
86
**Parameters:**
87
88
- `object` (Array|Object): The object to iterate over
89
- `iteratee` (Function, optional): The function invoked per iteration (defaults to identity function)
90
- `accumulator` (*, optional): The custom accumulator value
91
92
**Iteratee Function:**
93
94
The iteratee function receives four arguments:
95
1. `accumulator`: The current accumulator value (can be mutated)
96
2. `value`: The current element value
97
3. `key`: The current element key/index
98
4. `object`: The original object being transformed
99
100
**Returns:**
101
- `*`: The accumulated value
102
103
**Behavior:**
104
- Iteratee can exit iteration early by explicitly returning `false`
105
- If no accumulator provided, creates appropriate default:
106
- Arrays/TypedArrays: Creates new array with same constructor
107
- Objects: Creates plain object or preserves prototype chain
108
- Other values: Creates empty object `{}`
109
- Handles sparse arrays as dense arrays (undefined values become 'undefined')
110
- Works with both arrays and objects seamlessly
111
112
**Usage Examples:**
113
114
```javascript
115
import _ from "lodash";
116
const { transform } = _;
117
// Array transformation with early exit
118
const result1 = transform([2, 3, 4], function(result, n) {
119
result.push(n * n);
120
return n % 2 == 0; // Stop after finding first even number
121
}, []);
122
// => [4, 9]
123
124
// Object property grouping
125
const result2 = transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
126
(result[value] || (result[value] = [])).push(key);
127
}, {});
128
// => { '1': ['a', 'c'], '2': ['b'] }
129
130
// Auto-accumulator creation for arrays
131
const result3 = transform([1, 2, 3], function(result, value, index) {
132
result[index] = value * 2;
133
});
134
// => [2, 4, 6]
135
136
// Auto-accumulator creation for objects
137
const result4 = transform({ a: 1, b: 2 }, function(result, value, key) {
138
result[key.toUpperCase()] = value;
139
});
140
// => { A: 1, B: 2 }
141
142
// Constructor preservation for typed arrays
143
const typedArray = new Int32Array([1, 2, 3]);
144
const result5 = transform(typedArray, function(result, value, index) {
145
result[index] = value * 2;
146
});
147
// => Int32Array [2, 4, 6]
148
149
// Working with custom constructors
150
function Person(name) { this.name = name; }
151
Person.prototype.greet = function() { return 'Hello!'; };
152
const person = new Person('John');
153
154
const result6 = transform(person, function(result, value, key) {
155
if (key !== 'name') return;
156
result[key] = value.toUpperCase();
157
});
158
// => Person { name: 'JOHN' } (preserves prototype)
159
```