Lodash _.setWith() Method
Last Updated :
09 Nov, 2023
Lodash _.setWith() method is similar to _.set() method except that it accepts customizer which is invoked to produce the objects of path. And if the customizer returns undefined path creation is handled by the method instead.
Syntax:
_.setWith(object, path, value, customizer)
Parameters:
This method accepts four parameters as mentioned above and described below:
- object: It is the function that modifies the object.
- path: It sets the path of the property.
- value: It is used to set the values.
- customizer: It is the function to customize the assigned values.
Return Value:
This method returns the object.
Example 1: In this example, the code uses the Lodash library to set a nested property on an object and create the intermediate objects if they don’t exist, using the _.setWith
method.
Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
javascript
const _ = require( "lodash" );
let object = {};
let st_elem = _.setWith(object,
'[0][3]' , 'd' , Object);
console.log(st_elem);
|
Output:
{ '0': { '3': 'd' } }
Example 2: In this example, the code requires the Lodash library and utilizes the _.setWith
method to set a deep property within an object, and then it displays the modified object in the console.
javascript
const _ = require( "lodash" );
let object = {};
let st_elem = _.setWith(object,
'[0][1][2]' , 'a' , Object);
console.log(st_elem);
|
Output:
{ '0': {'1': { '2': 'a' } } }
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...