Lodash _.defaults() Method

The Lodash _.defaults() Method assign properties of source objects to the destination object for all destination properties that resolve to undefined. Source objects are applied from left to right. Once a property is set, additional values of the same property are ignored. This method mutates the object.

Syntax:

_.defaults( dest_object, [src_obj])

Parameters: This method accepts two parameters as mentioned above and described below:

  • dest_object: This is the destination object.
  • src_obj: These are the source objects.

Return Value: This method returns an object.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining Lodash variable 
const _ = require('lodash'); 
  
a = _.defaults({ 'gfg': 3 }, 
    { 'geek': 1 }, { 'gfg': 6 });
  
console.log(a);

chevron_right


Output:

{ gfg: 3, geek: 1 }

Example 2: 

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining Lodash variable 
const _ = require('lodash'); 
  
a = _.defaults({ 'a': 3 }, { 'b': 1 }, 
    { 'c': 5 }, { 'd': 5 }, { 'e': 5 });
  
console.log(a);

chevron_right


Output:

{ a: 3, b: 1, c: 5, d: 5, e: 5 }

Example 3: 

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining Lodash variable 
const _ = require('lodash'); 
  
a = _.defaults({ 'a': 'first setting'}, 
               { 'a': 'second setting but doesn't changes'});
console.log(a);

chevron_right


Output:

{ a: 'first setting' }

Note: This will not work in normal JavaScript because it requires the lodash library to be installed and can be installed using the following command:

npm install lodash

.

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.