To achieve this, there are several different solutions:
1 - Built-in javascript for-in loop :
var result = {}; for(var key in obj1) result[key] = obj1[key]; for(var key in obj2) result[key] = obj2[key];
2 - Object.keys() :
var result = {}; Object.keys(obj1).forEach((key) => result[key] = obj1[key]); Object.keys(obj2).forEach((key) => result[key] = obj2[key]);
3 - Object.assign() :
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: no support, Edge: (Yes), Opera: 32, Safari: 9)
var result = Object.assign({},obj1, obj2);
4 - Destruction purpose :
A new possible solution to achieve this goal is the use of Destructuring Assignment , which is partially standardized:
Destructuring destination syntax is a JavaScript expression that allows you to retrieve data from arrays or objects into separate variables.
Using this new syntax, you can merge / merge different objects into one object as follows:
var result = { ...obj1, ...obj2 };
5 - extend the jQuery or lodash :
var result={}; // using jQuery extend $.extend(result, obj1, obj2); // using lodash _.extend(result, obj1, obj2);
6 - lodash merge function :
var result=_.merge(obj1, obj2);
Update 1:
Just keep in mind that when using a for in loop in your native JavaScript, you need to know about your environment in terms of possible prototype changes in core JavaScript objects and global data types. For example, if you use js lib, which adds new material to Array.prototype or Object.prototype .
But if you want to prevent these possible added materials from polluting your objects in for in loops, you can do:
for(var key in obj1){ if(obj1.hasOwnProperty(key)){ result[key]=obj1[key]; } }
Update 2:
I updated my answer and added solution number 4, which is a new JavaScript feature, but not yet fully standardized. I use it with Babeljs , which is the compiler for writing next-generation JavaScript.