Open In App

Lodash _.update() Method

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:

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.




// Requiring the lodash library
const _ = require("lodash");
 
// The source object
let obj = { cpp: [{ java: { python: 3 } }] };
 
// Use of _.update() method
_.update(obj, "cpp[0].java.python", function (n) {
    return n * n;
});
 
// return the new object
console.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.




// 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 object
console.log(obj.html[0].css.javascript);

Output:

0

Article Tags :