Open In App

Lodash _.cloneWith() Method

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Lodash _.cloneWith() method of Lang in lodash is similar to the _.clone() method and the only difference is that it accepts a customizer which is called in order to generate cloned value. Moreover, if the customizer used here returns undefined then the cloning is dealt with by the method instead.

Note:

The customizer used here can be called with up to four arguments namely value, index|key, object, and stack.

Syntax:

_.cloneWith(value, [customizer]);

Parameters:

  • value: It is the value to be compared.
  • customizer: It is the other value to be compared.

Return Value:

  • This method returns a cloned value.

Example 1: In this example, we are cloning the given array with the customizer function and printing the result in the console.

JavaScript
// Requiring lodash library
const _ = require('lodash');

// Creating a function customizer
function customizer(val) {
    if (_.isElement(val)) {
        return val.cloneNode(false);
    }
}

// Defining value parameter
let value = [1, 2, 3];

// Calling cloneWith() method
let cloned_value = _.cloneWith(value, customizer);

// Displays output
console.log(cloned_value);

Output:

[ 1, 2, 3 ]

Example 2: In this example, we are cloning the given array with the customizer function and printing the result in the console.

JavaScript
// Requiring lodash library
const _ = require('lodash');

// Creating a function customizer
function customizer(val) {
    if (_.isElement(val)) {
        return val.cloneNode(false);
    }
}

// Defining value parameter
let value = ['Geeks', 'for', 'Geeks'];

// Calling cloneWith() method
let cloned_value = _.cloneWith(value, customizer);

// Displays output
console.log(cloned_value);

Output:

[ 'Geeks', 'for', 'Geeks' ]

Next Article

Similar Reads