Thursday, November 28, 2024
Google search engine
HomeLanguagesJavascriptLodash _.set() Method

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:

  • 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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments