The _.assignWith() method of Object in lodash is similar to the _.assign method and the only difference is that it accepts customizer which is called in order to generate assigned value. Moreover, if the customizer used here returns undefined then the assignment is dealt with by the method instead.
Note:
- The customizer used here can be called with five arguments namely objValue, srcValue, key, object, and source.
- The object used here is altered by this method.
Syntax:
_.assignWith(object, sources, [customizer])
Parameters: This method accepts three parameters as mentioned above and described below:
- object: It is the destination object.
- sources: It is the source of objects.
- customizer: It is the function that customizes assigned values.
Return Value: This method returns the object.
Below examples illustrate the Lodash _.assignWith() method in JavaScript:
Example 1:
Javascript
// Requiring lodash library const _ = require( 'lodash' ); // Defining a function customizer function customizer(objectVal, sourceVal) { return _.isUndefined(objectVal) ? sourceVal : objectVal; } // Calling assignWith method with its parameter let obj = _.assignWith({ 'neveropen' : 13 }, { 'GFG' : 4 }, customizer); // Displays output console.log(obj); |
Output:
{ neveropen: 13, GFG: 4 }
Example 2:
Javascript
// Requiring lodash library const _ = require( 'lodash' ); // Defining a function customizer function customizer(objectVal, sourceVal) { return _.isUndefined(objectVal) ? sourceVal : objectVal; } // Defining a function Num1 function Num1() { this .i = 11; } // Defining a function Num2 function Num2() { this .j = 12; } // Defining prototype of above functions Num1.prototype.k = 13; Num2.prototype.l = 14; // Calling assignWith method with its parameter let obj = _.assignWith({ 'i' : 10 }, new Num1, new Num2,customizer); // Displays output console.log(obj); |
Output:
{ i: 10, j: 12 }
Reference: https://lodash.com/docs/4.17.15#assignWith