Deep Merge Two Objects Using Recursive Function
This approach involves recursively traversing the objects and merging their properties. When encountering nested objects, the function calls itself to perform a deep merge.
Syntax:
function deepMerge<T>(target: T, ...sources: Partial<T>[]): T {
// Implementation
}
Example: Recursive Function Approach
In this example, we have two objects obj1 and obj2 with nested properties. We use a recursive function deepMerge to merge these objects deeply.
function isObject(item: any) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
function deepMerge(target: any, ...sources: any[]): any {
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
deepMerge(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return deepMerge(target, ...sources);
}
// Driver code
const obj1 = { a: { b: 1 } };
const obj2 = { a: { c: 2 } };
const merged = deepMerge({}, obj1, obj2);
console.log(merged); // Output: { a: { b: 1, c: 2 } }
Output:
{ a: { b: 1, c: 2 } }
How to Deep Merge Two Objects in TypeScript ?
Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore various approaches to deep merging objects in TypeScript, along with their syntax and examples.
Table of Content
- Deep Merge Two Objects Using Recursive Function
- Deep Merge Two Objects using Spread Operator
- Deep Merge Two Objects using Libraries like Lodash
- Using ES6 Maps for Tracking and Merging