Lodash _.update() method accepts an updater to produce the value to set. This method uses _.updateWith() function to customize path creation. It is almost the same as the _.set() function.
Syntax:
_.update(object, path, updater);
Parameters:
- object: This parameter holds the object to modify.
- path: This parameter holds the path of the property to set. It will be an array or string.
- updater: This is the function to produce the updated value.
Return Value:
This method returns the new object.Â
Example 1: In this example, we are updating the value of an object by using the _.update() method.
Javascript
// Requiring the lodash libraryconst _ = require("lodash");Â
// The source objectlet obj = { cpp: [{ java: { python: 3 } }] };Â
// Use of _.update() method_.update(obj, "cpp[0].java.python", function (n) {Â Â Â Â return n * n;});Â
// return the new objectconsole.log(obj.cpp[0].java.python); |
Output:
9
Example 2:Â In this example, we are updating the value of an object which is not present in that object and according the function which is passed in the _.update() method it is returning 0.
Javascript
// Requiring the lodash library const _ = require("lodash");Â
// The source object let obj = { 'cpp': [{ 'java': { 'python': 3 } }] };Â
// Use of _.update() method _.update(obj, 'html[0].css.javascript',    function (n) { return n ? n + 1 : 0; });Â
// return the new objectconsole.log(obj.html[0].css.javascript); |
Output:
0
