add after ary assign assignIn assignInWith assignWith at before bind bindAll bindKey camelCase capitalize castArray ceil chain chunk clamp clone cloneDeep cloneDeepWith cloneWith compact concat conformsTo countBy create curry curryRight debounce deburr defaults defaultsDeep defer delay difference divide drop dropRight each eachRight endsWith entries entriesIn eq escape every extend extendWith fill filter find findIndex findKey findLast findLastIndex findLastKey first flatMap flatMapDeep flatMapDepth flatten flattenDeep flattenDepth flip floor forEach forEachRight forIn forInRight forOwn forOwnRight fromPairs functions functionsIn get groupBy gt gte has hasIn head inRange includes indexOf initial intersection invert invertBy invoke invokeMap isArguments isArray isArrayBuffer isArrayLike isArrayLikeObject isBoolean isBuffer isDate isElement isEmpty isEqual isEqualWith isError isFinite isFunction isInteger isLength isMap isMatch isMatchWith isNaN isNative isNil isNull isNumber isObject isObjectLike isPlainObject isRegExp isSafeInteger isSet isString isSymbol isTypedArray isUndefined isWeakMap isWeakSet join kebabCase keyBy keys keysIn last lastIndexOf lowerCase lowerFirst lt lte map mapKeys mapValues max maxBy mean meanBy memoize merge mergeWith min minBy multiply negate nth omit omitBy once orderBy overArgs pad padEnd padStart parseInt partial partialRight partition pick pickBy pull pullAll pullAllBy pullAllWith pullAt random rearg reduce reduceRight reject remove repeat replace rest result reverse round sample sampleSize set setWith shuffle size slice snakeCase some sortBy sortedIndex sortedIndexOf sortedLastIndex sortedLastIndexOf sortedUniq split spread startCase startsWith subtract sum sumBy tail take takeRight tap template throttle thru toArray toFinite toInteger toLength toLower toNumber toPairs toPairsIn toPlainObject toSafeInteger toString toUpper transform trim trimEnd trimStart truncate unary unescape union uniq uniqBy uniqWith unset unzip unzipWith update updateWith upperCase upperFirst values valuesIn without words wrap wrapperAt wrapperChain wrapperCommit wrapperFlatMap wrapperLodash wrapperNext wrapperPlant wrapperReverse wrapperToIterator wrapperValue xor zip zipObject zipObjectDeep zipWith

Lodash _.assignInWith

Overview

The lodash _.assignInWith method is a powerful utility that fills a gap in the functionality provided by the native JavaScript Object.assign() method. Like Object.assign(), _.assignInWith() copies the values of all enumerable own properties from one or more source objects to a target object. However, it differs in two key ways:

  1. It recursively copies nested object properties.
  2. It allows for a customizer function to be passed in, which gives fine-grained control over how the values are merged.

Usage

The _.assignInWith() method has the following function signature:

_.assignInWith(object, ...sources, customizer)

The first argument, object, is the target object that will receive the properties. The remaining arguments, sources, are the source objects from which the properties will be copied. Finally, customizer is an optional function that will be called to merge the values of any properties that already exist in the target object. If a customizer function is not provided, then the last sourced value for that property will overwrite earlier values.

Example

Here is a simple example that shows how the lodash _.assignInWith() method can be used:

const _ = require('lodash');
 
const target = {
    name: 'John',
    age: 40,
    address: {
        city: 'New York',
        street: '123 Main St'
    }
};
 
const source = {
    age: 50,
    address: {
        city: 'Boston'
    }
};
 
function customizer(objValue, srcValue, key, object, source) {
    // Merge `address` objects, but overwrite all other properties
    if (key === 'address') {
        return _.assignInWith({}, objValue, srcValue, customizer);
    }
}
 
const result = _.assignInWith(target, source, customizer);
console.log(JSON.stringify(result));

In this example, we start with a target object that has a name, age, and address property. We also have a source object that has a new age value and an updated city value for the address property. We then define a customizer function that will be called to handle the merging of the address property. This customizer function uses the lodash _.assignInWith() method recursively to merge the nested address objects.

When we run the code, we see that the result object has merged the age and address properties from the source object into the target object, resulting in the following output:

{
    "name": "John",
    "age": 50,
    "address": {
        "city": "Boston",
        "street": "123 Main St"
    }
}

Conclusion

The lodash _.assignInWith() method is a powerful utility that provides enhanced functionality for merging object properties. Its ability to recursively merge nested objects and its customizer function make it a valuable tool for managing complex data structures.