The _.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:
Javascript
// Requiring the lodash library const _ = require( "lodash" ); // The source object var 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:
Javascript
// Requiring the lodash library const _ = require( "lodash" ); // The source object var 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.