Lodash _.updateWith() Method
Last Updated :
09 Nov, 2023
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:
- 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.
- customizer: This parameter holds the function to customize assigned values.
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.
Javascript
const _ = require( "lodash" );
let obj = {};
let gfg = _.updateWith(obj, '[0][1]' ,
_.constant( 'y' ), 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.
Javascript
const _ = require( "lodash" );
let obj = { 'cpp' : [{ 'java' : { 'python' : 3 } }] };
_.updateWith(obj, 'cpp[0].java.python' ,
function (n) { return n * n; });
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.
Share your thoughts in the comments
Please Login to comment...