![]() |
Typically, in JavaScript, combining two objects is a commonplace thing to do, but when it involves intricate nesting, deep merging turns out to be necessary, deep merge is the activity of taking the attributes or features from multiple objects (which have nested objects) and creating a new object with merged values. These are the following approaches: Using Recursive FunctionThe recursive traveling through the items method is employed here in which properties are merged, for the deep merge for nested objects, the function calls itself. Syntax:function deepMerge(target, ...sources) { Example: In the example below we will see how we can merge two objects using the Recursive Function approach.
Output { a: { b: 1, c: 2 } } Using Spread OperatorObjects can be shallow copied using the spread operator (…), by combining recursion with spread operators, it is possible to obtain a deep merging of objects. Syntax:function deepMerge(target, ...sources) { Example: In the example below we will see how we can merge two objects using Spread Operator approach.
Output { a: { b: 1, c: 2 } } Using Libraries like LodashLodash has a merge function that does deep merging of objects, it handles its edge cases and complexities very well which makes it a dependable choice for deep merging. Syntax:import _ from 'lodash'; Example: In the example below we will see how we can merge two objects using Libraries like Lodash.
Output: { a: { b: 1, c: 2 } } |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 18 |