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.
Customizing Cloning of Specific Properties:
4.2.
JavaScript
4.3.
Handling Custom Objects During Cloning:
4.4.
JavaScript
4.5.
Transforming Cloned Values:
4.6.
JavaScript
4.7.
Excluding Certain Properties from Cloning:
4.8.
JavaScript
5.
Frequently Asked Questions
5.1.
How does _.cloneWith() differ from _.clone()?
5.2.
What types of values can be customized with _.cloneWith()?
5.3.
Does _.cloneWith() handle deep cloning?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.cloneWith() Method

Author Ravi Khorwal
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Customizing the cloning process for objects and arrays in JavaScript can be crucial, especially when dealing with special types of data or when specific cloning behavior is required. Lodash's _.cloneWith() method provides a solution for this by allowing a customizer function to define how the cloning is performed. 

Lodash _.cloneWith() Method

This method is particularly useful for creating shallow copies of objects or arrays with a custom touch.

Why This Function is Used

The _.cloneWith() function is used to create a shallow copy of an object or array while enabling customization of the cloning process. This is essential in situations where you need to modify the cloning behavior for certain elements, handle custom object types, or perform transformations on the cloned values. Unlike deep cloning, _.cloneWith() provides a more lightweight approach, focusing on the top-level elements.

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: 

_.cloneWith(value, [customizer])

Parameters:

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

Return Value: 

Returns the shallow cloned value with custom behavior applied.

Examples 

Customizing Cloning of Specific Properties:

  • JavaScript

JavaScript

var _ = require('lodash');

function customClone(value) {

 if (_.isDate(value)) {

   return new Date(value);

 }

}

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

var clonedObject = _.cloneWith(object, customClone);

console.log(clonedObject.a instanceof Date);

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

console.log(clonedObject.b);              

Output

true
false
'normal value'


Demonstrates customizing the cloning of date properties in an object.

Handling Custom Objects During Cloning:

  • JavaScript

JavaScript

function CustomType(value) {

 this.value = value;

}

var customObject = new CustomType('original');

var clonedCustom = _.cloneWith(customObject, (val) => {

 if (val instanceof CustomType) return new CustomType('cloned');

});

console.log(clonedCustom.value);

Output: 

'cloned'


Shows custom handling for a custom object type during cloning.

Transforming Cloned Values:

  • JavaScript

JavaScript

var data = { num: 1, str: 'hello' };

var transformClone = (val) => {

 if (_.isString(val)) return val.toUpperCase();

};

var clonedData = _.cloneWith(data, transformClone);

console.log(clonedData.num);

console.log(clonedData.str);

Output

1
'HELLO'


An example of transforming values during the cloning process.

Excluding Certain Properties from Cloning:

  • JavaScript

JavaScript

var complexObject = { a: 1, b: { c: 2 }, d: [3, 4] };

var excludeB = (val, key) => {

 if (key === 'b') return {};

};

var clonedObject = _.cloneWith(complexObject, excludeB);

console.log(clonedObject.b);

console.log(clonedObject.d);

Output: 

{}
[3, 4] (unchanged)


Demonstrates excluding a specific property during cloning while keeping others intact.

Frequently Asked Questions

How does _.cloneWith() differ from _.clone()?

_.cloneWith() allows for a customizer function to define specific cloning behavior for elements, whereas _.clone() performs a standard shallow clone without customization.

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

The customizer function in _.cloneWith() can target any type of value within the object or array, including nested objects, arrays, and primitive values.

Does _.cloneWith() handle deep cloning?

No, _.cloneWith() performs a shallow clone. For deep cloning with customization, use _.cloneDeepWith().

Conclusion

Lodash's _.cloneWith() method offers an effective way to create shallow copies of objects or arrays while providing the flexibility to customize the cloning process. It's particularly useful for handling special data types or applying specific transformations during cloning.

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