Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Deeply Setting Default Values:
4.2.
JavaScript
4.3.
Nested Objects with Multiple Sources:
4.4.
JavaScript
4.5.
Initializing Deeply Nested Settings:
4.6.
JavaScript
4.7.
Defaults in Complex Data Structures:
4.8.
JavaScript
5.
Frequently Asked Questions
5.1.
How does _.defaultsDeep() differ from _.defaults()?
5.2.
Does _.defaultsDeep() perform a deep clone of source properties?
5.3.
Can _.defaultsDeep() handle arrays in objects?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.defaultsDeep() Method

Author Riya Singh
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

In complex programming scenarios, particularly when dealing with nested objects or configurations, there's often a need to assign default values deeply within the structure of an object. Lodash's _.defaultsDeep() method addresses this requirement. It recursively assigns default properties to an object, filling in undefined properties in the object with the first value found in a series of source objects. 

Lodash _.defaultsDeep() Method

This method is particularly useful in scenarios where nested configurations or settings need default values at multiple levels of depth.

Why This Function is Used

The _.defaultsDeep() function is used to fill in undefined properties in an object with values from subsequent source objects, but unlike _.defaults(), it does this recursively. This ensures that not just top-level properties, but also deeply nested properties in an object, can be assigned default values. It's particularly useful in complex settings and data structures where nested properties require initialization with default values.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax, Parameter and Return Value

Syntax: 

_.defaultsDeep(object, [sources])

Parameters:

  • object (Object): The destination object.
     
  • [sources] (...Object): The source objects.

Return Value: 

(Object) - Returns the modified object.

Examples 

Deeply Setting Default Values:

  • JavaScript

JavaScript

var _ = require('lodash');

var config = { 'settings': { 'width': 100 } };

var defaultConfig = { 'settings': { 'width': 200, 'height': 300 }, 'theme': 'light' };

_.defaultsDeep(config, defaultConfig);

console.log(config);

Output:

{ 'settings': { 'width': 100, 'height': 300 }, 'theme': 'light' }


Demonstrates setting default values in a nested configuration object.

Nested Objects with Multiple Sources:

  • JavaScript

JavaScript

var object = { 'a': { 'b': 2 } };

var defaults = { 'a': { 'b': 3, 'c': 3 } };

var moreDefaults = { 'a': { 'c': 4 }, 'd': 4 };

_.defaultsDeep(object, defaults, moreDefaults);

console.log(object);

Output: 

{ 'a': { 'b': 2, 'c': 3 }, 'd': 4 }


Shows how _.defaultsDeep() assigns values from multiple source objects to a nested object.

Initializing Deeply Nested Settings:

  • JavaScript

JavaScript

var userSettings = { 'preferences': { 'theme': 'dark' } };

var systemDefaults = { 'preferences': { 'theme': 'light', 'fontSize': 'medium' }, 'notifications': true };

_.defaultsDeep(userSettings, systemDefaults);

console.log(userSettings);

Output: 

{ 'preferences': { 'theme': 'dark', 'fontSize': 'medium' }, 'notifications': true }


An example of initializing deeply nested user settings with default values.

Defaults in Complex Data Structures:

  • JavaScript

JavaScript

var project = {

 name: 'My Project',

 config: {

   version: '1.0',

   build: { optimized: false }

 }

};

var defaultProjectConfig = {

 config: {

   build: { optimized: true, debug: true },

   environment: 'development'

 }

};

_.defaultsDeep(project, defaultProjectConfig);

console.log(project);

Output: 

{ name: 'My Project', config: { version: '1.0', build: { optimized: false, debug: true }, environment: 'development' } }


Demonstrates using _.defaultsDeep() for complex data structures in project configuration.

Frequently Asked Questions

How does _.defaultsDeep() differ from _.defaults()?

While _.defaults() only fills in undefined top-level properties, _.defaultsDeep() does so recursively, affecting nested objects as well.

Does _.defaultsDeep() perform a deep clone of source properties?

_.defaultsDeep() does a shallow copy of each source property. For properties that are objects, it creates a new object, but if the property is another type, like an array, it simply copies the reference.

Can _.defaultsDeep() handle arrays in objects?

For arrays within objects, _.defaultsDeep() assigns them as they are, without merging their contents. If a default array is expected to merge with an array in the object, a custom implementation is required.

Conclusion

Lodash's _.defaultsDeep() method is an effective tool for initializing objects with default values, including deeply nested properties. It's particularly valuable in complex settings where configurations or data structures span multiple levels and require comprehensive defaulting.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Lodash _.escapeRegExp() Method
Next article
Lodash _.conforms() Method
Live masterclass