Skip to content
Related Articles
Open in App
Not now

Related Articles

Lodash _.cloneWith() Method

Improve Article
Save Article
  • Last Updated : 18 Sep, 2020
Improve Article
Save Article

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.

The _.cloneWith() method of Lang in lodash is similar to _.clone() method and the only difference is that it accepts customizer which is called in order to generate cloned value. Moreover, if the customizer used here returns undefined then the cloning is dealt 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: This method accepts two parameters as mentioned above and described below:

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

Return Value: This method returns cloned value.

Example 1:

Javascript




// Requiring lodash library
const _ = require('lodash');
  
// Creating a function customizer
function customizer(val) {
  if (_.isElement(val)) {
    return val.cloneNode(false);
  }
}
  
// Defining value parameter
var value = [1, 2, 3];
  
// Calling cloneWith() method
var cloned_value = _.cloneWith(value, customizer);
  
// Displays output
console.log(cloned_value);


Output:

[ 1, 2, 3 ]

Example 2:

Javascript




// Requiring lodash library
const _ = require('lodash');
  
// Creating a function customizer
function customizer(val) {
  if (_.isElement(val)) {
    return val.cloneNode(false);
  }
}
  
// Defining value parameter
var value = ['Geeks', 'for', 'Geeks'];
  
// Calling cloneWith() method
var cloned_value = _.cloneWith(value, customizer);
  
// Displays output
console.log(cloned_value);


Output:

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

Example 3: Using isInteger() method as customizer.

Javascript




// Requiring lodash library
const _ = require('lodash');
  
// Creating a function int which acts as
// customizer
function int(x) {
 if (_.isInteger(x)) {
   return true;
   }
}
  
// Calling cloneWith() method along with
// its parameter
var cloned_value = _.cloneWith({ gfg: 5, 
        geeksforgeeks: 6}, int);
  
// Displays output
console.log(cloned_value);


Output:

{ gfg: 5, geeksforgeeks: 6 }

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!