0
# lodash.update
1
2
The lodash.update method exported as a Node.js module for updating object properties at specified paths using an updater function. This package provides deep property modification capabilities within nested objects and arrays through dot notation or bracket notation paths, with the updater function receiving the current value and returning the new value. The method mutates the original object and creates any missing intermediate properties along the path.
3
4
## Package Information
5
6
- **Package Name**: lodash.update
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.update`
10
11
## Core Imports
12
13
```javascript
14
var update = require('lodash.update');
15
```
16
17
## Basic Usage
18
19
```javascript
20
var update = require('lodash.update');
21
22
// Basic property update with updater function
23
var object = { 'a': [{ 'b': { 'c': 3 } }] };
24
25
update(object, 'a[0].b.c', function(n) { return n * n; });
26
console.log(object.a[0].b.c);
27
// => 9
28
29
// Creating missing properties with updater function
30
update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
31
console.log(object.x[0].y.z);
32
// => 0
33
```
34
35
## Capabilities
36
37
### Object Property Update
38
39
Updates object properties at specified paths using an updater function. The method mutates the original object and creates any missing intermediate properties along the path.
40
41
```javascript { .api }
42
/**
43
* This method is like `_.set` except that accepts `updater` to produce the
44
* value to set. Use `_.updateWith` to customize `path` creation. The `updater`
45
* is invoked with one argument: (value).
46
*
47
* **Note:** This method mutates `object`.
48
*
49
* @param {Object} object The object to modify.
50
* @param {Array|string} path The path of the property to set.
51
* @param {Function} updater The function to produce the updated value.
52
* @returns {Object} Returns `object`.
53
*/
54
function update(object, path, updater);
55
```
56
57
**Parameters:**
58
- `object` (Object): The object to modify
59
- `path` (Array|string): The path of the property to set. Can use dot notation (e.g., 'a.b.c'), bracket notation (e.g., 'a[0].b'), or array format (['a', '0', 'b'])
60
- `updater` (Function): The function to produce the updated value. Receives the current value at the path as its argument
61
62
**Returns:**
63
- (Object): Returns the modified `object`
64
65
**Behavior:**
66
- **Mutation**: Modifies the original object in-place
67
- **Path Creation**: Creates missing intermediate properties along the path
68
- **Array Handling**: Supports array indices in paths using bracket notation or numeric string keys
69
- **Updater Invocation**: The updater function receives the current value at the specified path (or `undefined` if the path doesn't exist)
70
71
**Usage Examples:**
72
73
```javascript
74
var update = require('lodash.update');
75
76
// Simple property update
77
var data = { count: 5 };
78
update(data, 'count', function(n) { return n + 1; });
79
console.log(data.count); // => 6
80
81
// Nested object update
82
var user = { profile: { stats: { score: 100 } } };
83
update(user, 'profile.stats.score', function(score) { return score * 2; });
84
console.log(user.profile.stats.score); // => 200
85
86
// Array element update
87
var collection = { items: [{ value: 10 }, { value: 20 }] };
88
update(collection, 'items[1].value', function(val) { return val + 5; });
89
console.log(collection.items[1].value); // => 25
90
91
// Creating new nested structure
92
var empty = {};
93
update(empty, 'a.b[0].c', function(val) { return val || 'default'; });
94
console.log(empty.a.b[0].c); // => 'default'
95
96
// Complex object transformation
97
var state = {
98
users: {
99
john: { posts: 5, active: true }
100
}
101
};
102
103
update(state, 'users.john.posts', function(posts) {
104
return posts + 1;
105
});
106
107
console.log(state.users.john.posts); // => 6
108
109
// Non-function updater (no change occurs)
110
var test = { value: 10 };
111
update(test, 'value', 'new value'); // Non-function updater
112
console.log(test.value); // => 10 (unchanged)
113
```
114
115
**Path Format Examples:**
116
117
```javascript
118
// Dot notation for object properties
119
update(obj, 'a.b.c', updater);
120
121
// Bracket notation for array indices
122
update(obj, 'a[0].b[1]', updater);
123
124
// Mixed notation
125
update(obj, 'users[0].profile.settings.theme', updater);
126
127
// Array format
128
update(obj, ['a', '0', 'b'], updater);
129
130
// Numeric keys as strings
131
update(obj, 'matrix.0.1', updater);
132
```
133
134
**Error Handling:**
135
136
The function handles various edge cases gracefully:
137
- Returns the original object unchanged if `object` is `null` or `undefined`
138
- Creates intermediate properties as plain objects `{}` or arrays `[]` based on the next key in the path
139
- Non-function updater values are converted to identity functions, resulting in no changes to the object (the current value is returned unchanged)
140
141
**Type Coercion:**
142
143
Path segments are automatically converted to appropriate types:
144
- Numeric strings become array indices when the target is an array
145
- String keys are used for object properties
146
- Symbol keys are preserved as-is and supported for object properties