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.
Custom Cloning of Special Objects:
4.2.
JavaScript
4.3.
Handling Custom Class Instances:
4.4.
JavaScript
4.5.
Transforming Nested Objects:
4.6.
JavaScript
4.7.
Excluding Specific Properties:
4.8.
JavaScript
4.9.
Output: 
5.
Frequently Asked Questions
6.
How does _.cloneDeepWith() differ from _.cloneDeep()?
6.1.
What types of values can be customized with _.cloneDeepWith()?
6.2.
Can _.cloneDeepWith() handle circular references?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.cloneDeepWith() Method

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

Introduction

In JavaScript, cloning complex objects with custom behavior or specific data types often requires more than a standard deep cloning process. Lodash's _.cloneDeepWith() method enhances the deep cloning capability by allowing you to specify a customizer function. 

Lodash _.cloneDeepWith() Method

This function determines how each element is cloned, providing greater control over the cloning process, especially for unique or complex objects.

Why This Function is Used

The _.cloneDeepWith() function is used for deep cloning objects or arrays while applying custom logic to handle specific types of data or conditions. This is particularly useful when working with objects that have nested structures, special types (like Date, RegExp, custom classes), or when you need to transform data during cloning. It allows for a tailored approach to deep cloning, accommodating unique requirements or constraints.

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: 

_.cloneDeepWith(value, [customizer])

Parameters:

  • value (Object|Array): The value to deeply clone.
     
  • [customizer] (Function): The function to customize cloning each element.

Return Value: 

Returns the deeply cloned value with custom behavior applied.

Examples 

Custom Cloning of Special Objects:

  • JavaScript

JavaScript

var _ = require('lodash');

var customCloner = function(value) {

 if (value instanceof Date) {

   return new Date(value);

 }

};

var object = { a: new Date(2020, 1, 1), b: 'normal value' };

var clonedObject = _.cloneDeepWith(object, customCloner);

console.log(clonedObject.a instanceof Date);

console.log(clonedObject.a === object.a);  

 Output: 

true
false


Demonstrates custom cloning for Date objects within a complex object.

Handling Custom Class Instances:

  • JavaScript

JavaScript

function MyClass(value) {

 this.value = value;

}

var myObject = new MyClass(10);

var clonedMyObject = _.cloneDeepWith(myObject, (val) => {

 if (val instanceof MyClass) return new MyClass(val.value);

});

console.log(clonedMyObject instanceof MyClass); // Output: true

console.log(clonedMyObject.value);          

    

Output: 

10


Shows custom handling for instances of a custom class during cloning.

Transforming Nested Objects:

  • JavaScript

JavaScript

var data = {

 nested: { num: 1, str: 'hello' }

};

var transformNested = (val) => {

 if (_.isObject(val)) return _.mapValues(val, v => v.toString());

};

var clonedData = _.cloneDeepWith(data, transformNested);

console.log(clonedData.nested.num);

console.log(clonedData.nested.str);

Output: 

'1'
'hello'


An example of transforming nested objects' values to strings during cloning.

Excluding Specific Properties:

  • JavaScript

JavaScript

var complexObject = {

 a: 1,

 b: { c: 2, d: 3 },

 e: [4, 5, 6]

};

var excludeB = (val) => {

 if (_.isEqual(val, complexObject.b)) return {};

};

var clonedWithoutB = _.cloneDeepWith(complexObject, excludeB);

console.log(clonedWithoutB.b);

Output: 

{}


Demonstrates excluding a specific property from being deeply cloned.

Frequently Asked Questions

How does _.cloneDeepWith() differ from _.cloneDeep()?

_.cloneDeepWith() allows for a customizer function that defines specific cloning behavior for each element, whereas _.cloneDeep() performs a standard deep clone without customization.

What types of values can be customized with _.cloneDeepWith()?

Any type of value within the object or array being cloned can be customized, including objects, arrays, primitives, and special objects like Date or custom class instances.

Can _.cloneDeepWith() handle circular references?

Handling circular references requires custom logic in the customizer function. Without it, _.cloneDeepWith() may result in a stack overflow error for objects with circular references.

Conclusion

Lodash's _.cloneDeepWith() method offers a powerful and flexible approach to deep cloning, providing the ability to customize the cloning process for each element. It is especially valuable when working with complex data structures or specific types that require tailored cloning logic.

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 _.pad() Method
Next article
Lodash _.cloneDeep() Method
Live masterclass