Lodash _.set() Method
Last Updated :
18 Oct, 2023
Lodash _.set() method is used to set the value at the path of the object and returns a new set object. if the path is not present with respect to that object then it will create that and put the value that is passed in the method. This method mutates the object.
Syntax:
_.set(object, path, value)
Parameters:
- 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.
- value: This parameter holds the value to set.
Return Value:
This method returns the new set object.
Example 1: In this example, we are setting a new value to the old object path.
Javascript
const _ = require( "lodash" );
let obj =
{ 'cpp' : [{ 'java' : { 'python' : 2012 } }] };
console.log(obj.cpp[0].java.python);
_.set(obj, 'cpp[0].java.python' , 2020);
console.log(obj.cpp[0].java.python);
|
Output:
2012
2020
Example 2: In this example, we are setting a new value to the old object path but as path is not present so it is creating a new path according to this and then assigning a value to it.
Javascript
const _ = require( "lodash" );
let obj =
{ 'cpp' : [{ 'java' : { 'python' : 2012 } }] };
_.set(obj, [ 'html' , '0' , 'css' , 'javascript' ], 2024);
console.log(obj.html[0].css.javascript);
|
Output:
2024
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...