Open In App

Lodash _.set() Method

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:

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.




// 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.




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

Article Tags :