Skip to content
Related Articles

Related Articles

Improve Article

Lodash _.set() Method

  • Last Updated : 16 Sep, 2020

The _.set() method is used to set the value at path of object and returns a new set object.

Syntax:

_.set(object, path, value)

Parameters: This method accepts three 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 array or string.
  • value: This parameter holds the value to set.

Return Value: This method returns the new set object.

Note: Here, const _ = require(‘lodash’) is used to import the lodash library into the file. 
 



Example 1:

Javascript




// Requiring the lodash library  
const _ = require("lodash");  
  
// The source object 
var obj = { 'cpp': [{ 'java': { 'python': 2012 } }] };
  
// 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:

2020

Example 2:  

Javascript




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

Note: This will not work in normal JavaScript because it requires the library lodash to be installed. 

Reference: https://lodash.com/docs/4.17.15#set

My Personal Notes arrow_drop_up
Recommended Articles
Page :