how to use the clonedeepwith function from lodash in javascript

The _.cloneDeepWith() function from lodash is used to create a deep clone of the given object, provided a customizer function to handle cloning of properties.

Here's an example of how to use the _.cloneDeepWith() function:

index.tsx
const _ = require('lodash');

const obj = {
  name: 'John',
  age: 42,
  address: {
    street: '123 Main St.',
    city: 'Anytown',
    state: 'CA'
  }
};

// Customizer function to clone only string values, leave other property types as-is
function customizer(value) {
  return _.isString(value) ? _.clone(value) : value;
}

const clonedObj = _.cloneDeepWith(obj, customizer);

console.log(clonedObj);
// Output: { name: 'John', age: 42, address: { street: '123 Main St.', city: 'Anytown', state: 'CA' } }
508 chars
22 lines

In the above example, we pass the obj variable and the customizer function to _.cloneDeepWith(). The customizer function checks each property value in the object and returns a deep clone of the value if it's a string, otherwise the function returns the value as-is. This ensures that only the string values in the object are cloned, leaving other property types as-is.

Finally, the cloned object clonedObj is logged to the console.

gistlibby LogSnag