0
# Lodash MapValues
1
2
Lodash MapValues provides the lodash `_.mapValues` method as a standalone Node.js module. This utility function enables developers to create new objects with the same keys as the original object but with values generated by running each property value through an iteratee function. The function supports various iteratee formats including functions, property names, and partial objects, making it highly versatile for data transformation tasks.
3
4
## Package Information
5
6
- **Package Name**: lodash.mapvalues
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.mapvalues`
10
11
## Core Imports
12
13
```javascript
14
var mapValues = require('lodash.mapvalues');
15
```
16
17
For modern environments with ES modules:
18
19
```javascript
20
import mapValues from 'lodash.mapvalues';
21
```
22
23
## Basic Usage
24
25
```javascript
26
var mapValues = require('lodash.mapvalues');
27
28
// Transform object values with a function
29
var users = {
30
'fred': { 'user': 'fred', 'age': 40 },
31
'pebbles': { 'user': 'pebbles', 'age': 1 }
32
};
33
34
var ages = mapValues(users, function(o) {
35
return o.age;
36
});
37
// => { 'fred': 40, 'pebbles': 1 }
38
39
// Use property name shorthand
40
var agesByProperty = mapValues(users, 'age');
41
// => { 'fred': 40, 'pebbles': 1 }
42
```
43
44
## Capabilities
45
46
### Object Value Transformation
47
48
Creates an object with the same keys as the input object and values generated by running each own enumerable string keyed property through an iteratee function.
49
50
```javascript { .api }
51
/**
52
* Creates an object with the same keys as `object` and values generated
53
* by running each own enumerable string keyed property of `object` thru
54
* `iteratee`. The iteratee is invoked with three arguments:
55
* (value, key, object).
56
*
57
* @param {Object} object The object to iterate over.
58
* @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
59
* @returns {Object} Returns the new mapped object.
60
*/
61
function mapValues(object, iteratee);
62
```
63
64
#### Parameters
65
66
- **`object`** (Object): The object to iterate over
67
- **`iteratee`** (Function|Object|string) [optional]: The function invoked per iteration. Can be:
68
- **Function**: Invoked with `(value, key, object)` arguments
69
- **String**: Property name for shorthand property access (e.g., `'age'`)
70
- **Object**: Partial object for partial matching
71
- **Undefined**: Defaults to identity function (returns values unchanged)
72
73
#### Return Value
74
75
- (Object): Returns the new mapped object with the same keys as the input object
76
77
#### Iteratee Function Signature
78
79
When using a function as the iteratee:
80
81
```javascript { .api }
82
/**
83
* @param {*} value The current property value
84
* @param {string} key The current property key
85
* @param {Object} object The source object being iterated
86
* @returns {*} The transformed value for this property
87
*/
88
function iteratee(value, key, object);
89
```
90
91
## Usage Examples
92
93
### Function Iteratee
94
95
Transform values using a custom function:
96
97
```javascript
98
var mapValues = require('lodash.mapvalues');
99
100
var users = {
101
'alice': { 'name': 'Alice', 'age': 25, 'active': true },
102
'bob': { 'name': 'Bob', 'age': 30, 'active': false }
103
};
104
105
// Extract and transform specific properties
106
var userSummaries = mapValues(users, function(user, key) {
107
return user.name + ' (' + user.age + ' years old)';
108
});
109
// => { 'alice': 'Alice (25 years old)', 'bob': 'Bob (30 years old)' }
110
111
// Calculate derived values
112
var userStatuses = mapValues(users, function(user) {
113
return user.active ? 'active' : 'inactive';
114
});
115
// => { 'alice': 'active', 'bob': 'inactive' }
116
```
117
118
### Property Name Shorthand
119
120
Use property name strings for simple property extraction:
121
122
```javascript
123
var products = {
124
'laptop': { 'name': 'Laptop', 'price': 999, 'category': 'electronics' },
125
'book': { 'name': 'Book', 'price': 29, 'category': 'education' }
126
};
127
128
// Extract prices using property shorthand
129
var prices = mapValues(products, 'price');
130
// => { 'laptop': 999, 'book': 29 }
131
132
// Extract categories
133
var categories = mapValues(products, 'category');
134
// => { 'laptop': 'electronics', 'book': 'education' }
135
```
136
137
### Object Iteratee (Partial Matching)
138
139
Use objects for partial matching patterns:
140
141
```javascript
142
var items = {
143
'item1': { 'type': 'book', 'genre': 'fiction', 'available': true },
144
'item2': { 'type': 'book', 'genre': 'non-fiction', 'available': false },
145
'item3': { 'type': 'dvd', 'genre': 'action', 'available': true }
146
};
147
148
// Check if items match specific criteria
149
var fictionBooks = mapValues(items, { 'type': 'book', 'genre': 'fiction' });
150
// => { 'item1': true, 'item2': false, 'item3': false }
151
```
152
153
### Complex Data Transformations
154
155
```javascript
156
var inventory = {
157
'warehouse-a': {
158
'items': ['laptop', 'mouse', 'keyboard'],
159
'capacity': 1000,
160
'location': 'Seattle'
161
},
162
'warehouse-b': {
163
'items': ['monitor', 'cable', 'speakers'],
164
'capacity': 500,
165
'location': 'Portland'
166
}
167
};
168
169
// Transform to summary format
170
var warehouseSummaries = mapValues(inventory, function(warehouse, key) {
171
return {
172
'id': key,
173
'itemCount': warehouse.items.length,
174
'utilization': (warehouse.items.length / warehouse.capacity * 100).toFixed(1) + '%',
175
'location': warehouse.location
176
};
177
});
178
// => {
179
// 'warehouse-a': { 'id': 'warehouse-a', 'itemCount': 3, 'utilization': '0.3%', 'location': 'Seattle' },
180
// 'warehouse-b': { 'id': 'warehouse-b', 'itemCount': 3, 'utilization': '0.6%', 'location': 'Portland' }
181
// }
182
```
183
184
## Error Handling
185
186
The function handles edge cases gracefully:
187
188
- **Null/undefined objects**: Returns empty object `{}`
189
- **Non-object inputs**: Treats as objects where possible, may return empty object for primitives
190
- **Missing properties**: Property shorthand returns `undefined` for missing properties
191
- **Iteratee errors**: Errors thrown in iteratee functions will propagate
192
193
```javascript
194
// Safe handling of null/undefined
195
mapValues(null, 'someProperty'); // => {}
196
mapValues(undefined, function(v) { return v; }); // => {}
197
198
// Handles missing properties gracefully
199
mapValues({ a: { x: 1 }, b: { y: 2 } }, 'x');
200
// => { a: 1, b: undefined }
201
```
202
203
## Performance Considerations
204
205
- **Property enumeration**: Only processes own enumerable string-keyed properties
206
- **Iteration order**: Not guaranteed to preserve property order in older JavaScript environments
207
- **Memory usage**: Creates a new object; does not modify the original
208
- **Large objects**: Performance scales linearly with the number of properties
209
210
## Related Functionality
211
212
This package is part of the modularized lodash ecosystem. Related packages include:
213
214
- `lodash.mapkeys` - Transform object keys instead of values
215
- `lodash.map` - Transform array elements
216
- `lodash.foreach` - Iterate without transformation
217
- `lodash` - Full lodash library with all utilities