Open In App

Lodash _.set() Method

Last Updated : 18 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Requiring the lodash library 
const _ = require("lodash");
 
// The source object
let obj =
    { 'cpp': [{ 'java': { 'python': 2012 } }] };
     
// Prinitng old object
// before using _.set method
console.log(obj.cpp[0].java.python);
 
// set the value by _.set() method
_.set(obj, 'cpp[0].java.python', 2020);
 
// return the new set object
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




// Requiring the lodash library 
const _ = require("lodash");
 
// The source object
let obj =
    { 'cpp': [{ 'java': { 'python': 2012 } }] };
 
// Set the value by _.set() method
_.set(obj, ['html', '0', 'css', 'javascript'], 2024);
 
// Return the new set object
console.log(obj.html[0].css.javascript);


Output:

2024


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads