Open In App

Lodash _.updateWith() Method

Lodash_.updateWith() method accepts a customizer function that is invoked to produce the objects of the path. If the customizer function returns undefined path creation is handled by the method instead. It is almost the same as the _.update() function.

Syntax:

_.updateWith(object, path, updater, [customizer])

Parameters:

This method accepts four parameters as mentioned above and described below:



Return Value:

This method returns the object.

Example 1: In this example, the code requires the Lodash library, defines an empty object obj, and utilizes the _.updateWith method to update the object by setting the value at path [0][1] to ‘y’. It then returns the new modified object and displays it in the console.






// Requiring the lodash library 
const _ = require("lodash"); 
 
// The source object
let obj = {};
 
// Use of _.updateWith() method
let gfg = _.updateWith(obj, '[0][1]',
    _.constant('y'), Object);
 
// Returning the new object
console.log(gfg);

Output:

{ '0': { '1': 'y' } }

Example 2: In this example, the code requires the Lodash library and operates on the source object obj, which contains a nested structure. It uses the _.updateWith method to update the value at the path ‘cpp[0].java.python’ by squaring the existing value. The updated value is then accessed and displayed in the console.




// Requiring the lodash library 
const _ = require("lodash"); 
 
// The source object
let obj = { 'cpp': [{ 'java': { 'python': 3 } }] };
 
// Use of _.updateWith() method
_.updateWith(obj, 'cpp[0].java.python',
    function(n) { return n * n; });
 
// Returning the updated object value
console.log(obj.cpp[0].java.python);

Output:

9

Note: This will not work in normal JavaScript because it requires the lodash library to be installed. 


Article Tags :