add after ary assign assignIn assignInWith assignWith at before bind bindAll bindKey camelCase capitalize castArray ceil chain chunk clamp clone cloneDeep cloneDeepWith cloneWith compact concat conformsTo countBy create curry curryRight debounce deburr defaults defaultsDeep defer delay difference divide drop dropRight each eachRight endsWith entries entriesIn eq escape every extend extendWith fill filter find findIndex findKey findLast findLastIndex findLastKey first flatMap flatMapDeep flatMapDepth flatten flattenDeep flattenDepth flip floor forEach forEachRight forIn forInRight forOwn forOwnRight fromPairs functions functionsIn get groupBy gt gte has hasIn head inRange includes indexOf initial intersection invert invertBy invoke invokeMap isArguments isArray isArrayBuffer isArrayLike isArrayLikeObject isBoolean isBuffer isDate isElement isEmpty isEqual isEqualWith isError isFinite isFunction isInteger isLength isMap isMatch isMatchWith isNaN isNative isNil isNull isNumber isObject isObjectLike isPlainObject isRegExp isSafeInteger isSet isString isSymbol isTypedArray isUndefined isWeakMap isWeakSet join kebabCase keyBy keys keysIn last lastIndexOf lowerCase lowerFirst lt lte map mapKeys mapValues max maxBy mean meanBy memoize merge mergeWith min minBy multiply negate nth omit omitBy once orderBy overArgs pad padEnd padStart parseInt partial partialRight partition pick pickBy pull pullAll pullAllBy pullAllWith pullAt random rearg reduce reduceRight reject remove repeat replace rest result reverse round sample sampleSize set setWith shuffle size slice snakeCase some sortBy sortedIndex sortedIndexOf sortedLastIndex sortedLastIndexOf sortedUniq split spread startCase startsWith subtract sum sumBy tail take takeRight tap template throttle thru toArray toFinite toInteger toLength toLower toNumber toPairs toPairsIn toPlainObject toSafeInteger toString toUpper transform trim trimEnd trimStart truncate unary unescape union uniq uniqBy uniqWith unset unzip unzipWith update updateWith upperCase upperFirst values valuesIn without words wrap wrapperAt wrapperChain wrapperCommit wrapperFlatMap wrapperLodash wrapperNext wrapperPlant wrapperReverse wrapperToIterator wrapperValue xor zip zipObject zipObjectDeep zipWith

Lodash _.cloneDeepWith

Overview

Overview:

Lodash is a popular JavaScript library that provides utility functions to enhance the functionality of vanilla JavaScript. One of its key methods is _.cloneDeepWith().

The _.cloneDeepWith() method creates a deep clone of a given object and allows applying a customizer function for each cloned property.

Syntax:

_.cloneDeepWith(value, [customizer])

Parameters:

  • value: It is the source object to clone deeply.
  • [customizer]: It can be an optional function that allows consolidating the behavior of cloneDeepWith() to customize the cloning process.

Return value:

The _.cloneDeepWith() method returns a deep copy of the evaluated object.

Behavior:

The _.cloneDeepWith() method is different from _.cloneDeep() as it enables customization of each property while cloning.

It performs a deep recursive clone of the given object, which means it clones every property of the object, including nested sub-objects.

The _.cloneDeepWith() method can clone any source object, including arrays, objects, Map, Set, and others.

Additionally, a customizer function can be passed as an optional parameter. This function allows overriding the default behavior of the cloning process.

If a customizer function is provided, _.cloneDeepWith() calls it for each source object property cloned. So, the customizer function can specify how to clone each property.

For instance, if the customizer function is designed to clone only the properties whose keys start with '_private', it will create a deep copy of those properties only, and leave the others uncloned.

Example:

Here is an example of using the _.cloneDeepWith() method with a customizer function:

const lodash = require('lodash'); var o1 = { a: [{ b: { c: 3 } }], d: { e: 4 } };

var o2 = lodash.cloneDeepWith(o1, function(value) { return lodash.isElement(value) ? value.cloneNode(true) : undefined; });

console.log(o2.a[0].b);

In the example, the cloneDeepWith() method is used to deep clone the o1 object. The customizer function specifies how to clone the properties of the objects, including the nested one.

The method returns a new object with the same structure and property values as the source object. The object in the variable o1 remains identical to the original object, whereas the object in o2 is a clone of o1.

Conclusion:

The _.cloneDeepWith() method is an essential tool for creating a deep clone of the given object, which is useful to prevent mutation of the original object. It provides multiple options to customize the cloning process, enabling greater flexibility on how objects can be cloned. This method is also part of Lodash, a popular JavaScript library that provides a wide range of high-performance, utility functions.