Lodash _.set() Method

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


Output:

2020

Example 2:  

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


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

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.