How to merge content of two or more objects in JavaScript?
Introduction
How to merge content of two or more objects in JavaScript?
Solution 1 - Use jQuery $.extend()
The merge performed by $.extend()
is not recursive by default; if a property of the first object is itself an object or array, it will be completely overwritten by a property with the same key in the second or subsequent object. The values are not merged. This can be seen in the example below by examining the value of banana. However, by passing true
for the first function argument, objects will be recursively merged.
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
// Merge object2 into object1
$.extend( object1, object2 );
console.log( JSON.stringify( object1 ) );
Result:
{"apple":0,"banana":{"price":200},"cherry":97,"durian":100}
Example - a deep merge
A deep merge will merge two objects recursively, modifying the first.
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
// Merge object2 into object1, recursively
$.extend( true, object1, object2 );
console.log( JSON.stringify( object1 ) );
Result:
{"apple":0,"banana":{"weight":52,"price":200},"cherry":97,"durian":100}
Solution 2 - Use concat()
for arrays
Assuming that you would like to merge two JSON arrays like below:
var json1 = [{id:1, name: 'xxx' ...}]
var json2 = [{id:2, name: 'xyz' ...}]
The solution is simply use JavaScript arrayconcat()
var finalObj = json1.concat(json2);
Latest Post
- Dependency injection
- Directives and Pipes
- Data binding
- HTTP Get vs. Post
- Node.js is everywhere
- MongoDB root user
- Combine JavaScript and CSS
- Inline Small JavaScript and CSS
- Minify JavaScript and CSS
- Defer Parsing of JavaScript
- Prefer Async Script Loading
- Components, Bootstrap and DOM
- What is HEAD in git?
- Show the changes in Git.
- What is AngularJS 2?
- Confidence Interval for a Population Mean
- Accuracy vs. Precision
- Sampling Distribution
- Working with the Normal Distribution
- Standardized score - Z score
- Percentile
- Evaluating the Normal Distribution
- What is Nodejs? Advantages and disadvantage?
- How do I debug Nodejs applications?
- Sync directory search using fs.readdirSync