Lodash _.merge() Method
_.merge offers deep merge functionality. It recursively combines properties from source objects into a brand new target object. This preserves the original target object and creates deep copies for nested objects, allowing independent modifications.
Example 1: Basic Usage
const _ = require('lodash');
let target = { a: 1, b: 2 };
let source = { b: 3, c: 4 };
let result = _.merge({}, target, source);
console.log(result);
Output:
{ a: 1, b: 3, c: 4 }
Example 2: Nested Objects
const _ = require('lodash');
let target = { a: { x: 1 }, b: 2 };
let source = { a: { y: 2 }, c: 3 };
let result = _.merge({}, target, source);
console.log(result);
Output:
{ a: { x: 1, y: 2 }, b: 2, c: 3 }
Difference Between _.assign() & _.merge() Method in Lodash
Lodash is a JavaScript library that works on the top of underscore.js. It helps in working with arrays, strings, objects, numbers, etc. It provides us with various inbuilt functions and uses a functional programming approach.