Lodash _.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:
- 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.
Example 1: In this example, we are checking whether the given value is undefined or not and return the value according to the custom function by the use of the lodash _.assignWith() method.
Javascript
const _ = require('lodash');
function customizer(objectVal, sourceVal) {
return _.isUndefined(objectVal) ? sourceVal : objectVal;
}
let obj = _.assignWith({ 'geeksforgeeks': 13 },
{ 'GFG': 4 }, customizer);
console.log(obj);
|
Output:
{ geeksforgeeks: 13, GFG: 4 }
Example 2: In this example, we are checking whether the given value is undefined or not and return the value according to the custom function by the use of the lodash _.assignWith() method.
Javascript
const _ = require('lodash');
function customizer(objectVal, sourceVal) {
return _.isUndefined(objectVal) ? sourceVal : objectVal;
}
function Num1() {
this.i = 11;
}
function Num2() {
this.j = 12;
}
Num1.prototype.k = 13;
Num2.prototype.l = 14;
let obj = _.assignWith({ 'i': 10 },
new Num1, new Num2, customizer);
console.log(obj);
|
Output:
{ i: 10, j: 12 }
Reference: https://lodash.com/docs/4.17.15#assignWith
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
30 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...