Open In App

Lodash _.cloneWith() Method

Improve
Improve
Like Article
Like
Save
Share
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' ]

Reference: https://lodash.com/docs/4.17.15#cloneWith



Last Updated : 03 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads