What is lodash.clonedeepwith?
The lodash.clonedeepwith package is a utility library that allows you to deeply clone values, with the ability to customize the cloning process. It is part of the Lodash library, which is a popular utility library for JavaScript.
What are lodash.clonedeepwith's main functionalities?
Deep Cloning with Customizer
This feature allows you to deeply clone an object while applying a custom transformation to each value. In this example, the customizer function doubles any number it encounters during the cloning process.
const cloneDeepWith = require('lodash.clonedeepwith');
const obj = { a: 1, b: { c: 2 } };
const customizer = (value) => {
if (typeof value === 'number') {
return value * 2;
}
};
const clonedObj = cloneDeepWith(obj, customizer);
console.log(clonedObj); // { a: 2, b: { c: 4 } }
Handling Circular References
This feature allows you to handle circular references in objects. In this example, the customizer function replaces circular references with the string 'Circular Reference'.
const cloneDeepWith = require('lodash.clonedeepwith');
const obj = { a: 1 };
obj.b = obj;
const customizer = (value) => {
if (value === obj) {
return 'Circular Reference';
}
};
const clonedObj = cloneDeepWith(obj, customizer);
console.log(clonedObj); // { a: 1, b: 'Circular Reference' }
Other packages similar to lodash.clonedeepwith
rfdc
The 'rfdc' (Really Fast Deep Clone) package is a lightweight and fast deep cloning library. It does not support customizers like lodash.clonedeepwith, but it is optimized for performance and can handle most deep cloning needs efficiently.
clone-deep
The 'clone-deep' package is another deep cloning library that supports deep cloning of objects, arrays, and other types. It is similar to lodash.clonedeepwith but does not offer the same level of customization through customizer functions.
deepcopy
The 'deepcopy' package is a deep cloning library that supports cloning of complex objects, including those with circular references. It is similar to lodash.clonedeepwith but does not provide a customizer function for transforming values during the cloning process.
lodash.clonedeepwith v4.5.0
The lodash method _.cloneDeepWith
exported as a Node.js module.
Installation
Using npm:
$ {sudo -H} npm i -g npm
$ npm i --save lodash.clonedeepwith
In Node.js:
var cloneDeepWith = require('lodash.clonedeepwith');
See the documentation or package source for more details.