You should use "Object.assign()"

There's no need to reinvent the wheel for such a simple use case of shallow merging.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj);       // { a: 1, b: 2, c: 3 }
console.log(o1);        // { a: 1, b: 2, c: 3 }, target object itself is changed
console.log(obj === o1) // true

Even the folks from Node.js say so:

_extend was never intended to be used outside of internal NodeJS modules. The community found and used it anyway. It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign.


Update:

You could use the spread operator

Since version 8.6, it's possible to natively use the spread operator in Node.js. Example below:

let o1 = { a: 1 };
let o2 = { b: 2 };
let obj = { ...o1, ...o2 }; // { a: 1, b: 2 }

Object.assign still works, though.


PS1: If you are actually interested in deep merging (in which internal object data -- in any depth -- is recursively merged), you can use packages like deepmerge, assign-deep or lodash.merge, which are pretty small and simple to use.

PS2: Keep in mind that Object.assign doesn't work with 0.X versions of Node.js. If you are working with one of those versions (you really shouldn't by now), you could use require("util")._extend as shown in the Node.js link above -- for more details, check tobymackenzie's answer to this same question.

Answer from Ricardo Nolde on Stack Overflow
Top answer
1 of 16
147

You should use "Object.assign()"

There's no need to reinvent the wheel for such a simple use case of shallow merging.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj);       // { a: 1, b: 2, c: 3 }
console.log(o1);        // { a: 1, b: 2, c: 3 }, target object itself is changed
console.log(obj === o1) // true

Even the folks from Node.js say so:

_extend was never intended to be used outside of internal NodeJS modules. The community found and used it anyway. It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign.


Update:

You could use the spread operator

Since version 8.6, it's possible to natively use the spread operator in Node.js. Example below:

let o1 = { a: 1 };
let o2 = { b: 2 };
let obj = { ...o1, ...o2 }; // { a: 1, b: 2 }

Object.assign still works, though.


PS1: If you are actually interested in deep merging (in which internal object data -- in any depth -- is recursively merged), you can use packages like deepmerge, assign-deep or lodash.merge, which are pretty small and simple to use.

PS2: Keep in mind that Object.assign doesn't work with 0.X versions of Node.js. If you are working with one of those versions (you really shouldn't by now), you could use require("util")._extend as shown in the Node.js link above -- for more details, check tobymackenzie's answer to this same question.

2 of 16
58

If using Node version >= 4, use Object.assign() (see Ricardo Nolde's answer).

If using Node 0.x, there is the built in util._extend:

var extend = require('util')._extend
var o = extend({}, {name: "John"});
extend(o,  {location: "San Jose"});

It doesn't do a deep copy and only allows two arguments at a time, but is built in. I saw this mentioned on a question about cloning objects in node: https://stackoverflow.com/a/15040626.

If you're concerned about using a "private" method, you could always proxy it:

// myutil.js
exports.extend = require('util')._extend;

and replace it with your own implementation if it ever disappears. This is (approximately) their implementation:

exports.extend = function(origin, add) {
    if (!add || (typeof add !== 'object' && add !== null)){
        return origin;
    }

    var keys = Object.keys(add);
    var i = keys.length;
    while(i--){
        origin[keys[i]] = add[keys[i]];
    }
    return origin;
};
🌐
DevGenius
blog.devgenius.io › combining-json-objects-in-javascript-node-js-abe84f492d0
Combining JSON Objects in JavaScript/Node.js | by Popa Vlad | Dev Genius
March 6, 2025 - // JSON objects to be merged const jsonObj1 = { name: "John", age: 25 }; const jsonObj2 = { city: "New York", hobby: "Coding" }; // Merge JSON objects const mergedJSON = Object.assign({}, jsonObj1, jsonObj2); console.log(mergedJSON);
Discussions

merge two JSON objects into one
Hello everyone 😃 I need to merge two JSON objects before I want to do my upload to the API. I found online that I have to use JSON Transfomer… is that node the best way to do this? If yes, can someone please provide me an example? I did my research on that topic but I was not able to find ... More on forum.knime.com
🌐 forum.knime.com
0
0
May 26, 2020
How to join two JSON Array objects in Node
How to join two JSON Array objects in Node. More on stackoverflow.com
🌐 stackoverflow.com
April 19, 2018
Merge two json objects if data match?
I have two json lists where I first want to match data, and then if match, replace with data from another key. json1: [ { "name": "abcd", "_id": "64a437767da5f6205aa0d4ef" }, { "name": "efgh", "_id": "64a437767da5f6205aa0d4a8" }, { "name": "ijkl", "_id": "64a437767da5f6205aa0d4sa" } ] json2: ... More on community.n8n.io
🌐 community.n8n.io
1
0
July 5, 2023
How to join two JavaScript Objects, without using JQUERY - Stack Overflow
I have two json objects obj1 and obj2, i want to merge them and crete a single json object. The resultant json should have all the values from obj2 and the values from obj1 which is not present in ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
npm
npmjs.com › package › json-merger
json-merger - npm
Latest version: 3.0.0, last published: a year ago. Start using json-merger in your project by running `npm i json-merger`. There are 31 other projects in the npm registry using json-merger.
      » npm install json-merger
    
Published   Feb 02, 2025
Version   3.0.0
Author   Niek Bosch
🌐
KNIME Community
forum.knime.com › knime analytics platform
merge two JSON objects into one - KNIME Analytics Platform - KNIME Community Forum
May 26, 2020 - Hello everyone 😃 I need to merge two JSON objects before I want to do my upload to the API. I found online that I have to use JSON Transfomer… is that node the best way to do this? If yes, can someone please provide me an example? I did my research on that topic but I was not able to find ...
🌐
Quora
quora.com › How-can-I-add-two-JSON-objects-into-one-object-JavaScript
How to add two JSON objects into one object JavaScript - Quora
Answer (1 of 4): The Spread syntax could be very helpful here, depending upon exactly what you want to do. [code]let obj1 = { a : ‘aValue’, b : ‘bValue’ }; let obj2 = {c : ‘cValue’, d : ‘dValue’, a : 'obj2AValue' }; let combined = { …obj1, …obj2 }; [/code]Note that if there ...
🌐
techtutorialsx
techtutorialsx.wordpress.com › 2020 › 09 › 06 › javascript-merge-json-objects
JavaScript merge JSON objects – techtutorialsx
January 25, 2025 - Then we will take care of the actual merging of the JSON objects. So, we will start by defining a new object with brackets. Then, we will use the spread operator “…” to copy the properties of each original object to the new one. We are using this syntax to merge two objects, but we could merge more objects in the same assignment operation.
🌐
npm
npmjs.com › package › merge-json
merge-json - npm
August 26, 2016 - Merge two JSON Objects into one new Object. Latest version: 0.1.0-b.3, last published: 9 years ago. Start using merge-json in your project by running `npm i merge-json`. There are 65 other projects in the npm registry using merge-json.
      » npm install merge-json
    
Published   Aug 26, 2016
Version   0.1.0-b.3
Author   Jacob Fricke
Find elsewhere
🌐
Research Hubs
researchhubs.com › post › computing › javascript › merge-content-of-objects.html
How to merge content of two or more objects in JavaScript?
var object1 = { apple: 0, banana: ... [{id:1, name: 'xxx' ...}] var json2 = [{id:2, name: 'xyz' ...}] The solution is simply use JavaScript arrayconcat() var finalObj = json1.concat(json2); Dependency injection · Directives and Pipes · Data binding · HTTP Get vs....
🌐
npm
npmjs.com › package › deepmerge-json
deepmerge-json - npm
August 2, 2022 - Latest version: 1.5.0, last published: 3 years ago. Start using deepmerge-json in your project by running `npm i deepmerge-json`. There are 22 other projects in the npm registry using deepmerge-json.
      » npm install deepmerge-json
    
Published   Aug 02, 2022
Version   1.5.0
Author   Kleber Silva
🌐
Futurestud.io
futurestud.io › tutorials › node-js-how-to-merge-objects
Node.js — How to Merge Objects - Future Studio
April 2, 2020 - Merge two or more objects into a new objects like this: const first = { name: 'Marcus', sub: { eyes: 'blue' } } const second = { name: 'Node.js', sub: { hair: 'brown' } } const spread = { ...first, ...second } // { name: 'Node.js', // sub: { hair: 'brown' } // }
🌐
Quora
quora.com › How-do-I-combine-different-JSON-files-in-JavaScript-urgent
How to combine different JSON files in JavaScript urgent - Quora
Answer (1 of 2): Can you please elaborate more or drop the question on Stack Overflow - Where Developers Learn, Share, & Build Careers.
Top answer
1 of 6
264

There are couple of different solutions to achieve this:

1 - Native javascript for-in loop:

const result = {};
let key;

for (key in obj1) {
  if(obj1.hasOwnProperty(key)){
    result[key] = obj1[key];
  }
}

for (key in obj2) {
  if(obj2.hasOwnProperty(key)){
    result[key] = obj2[key];
  }
}

2 - Object.keys():

const 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)

const result = Object.assign({}, obj1, obj2);

4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):

Defined in several sections of the specification: Array Initializer, Argument Lists

Using this new syntax you could join/merge different objects into one object like this:

const result = {
  ...obj1,
  ...obj2,
};

5 - jQuery.extend(target, obj1, obj2):

Merge the contents of two or more objects together into the first object.

const target = {};

$.extend(target, obj1, obj2);

6 - jQuery.extend(true, target, obj1, obj2):

Run a deep merge of the contents of two or more objects together into the target. Passing false for the first argument is not supported.

const target = {};

$.extend(true, target, obj1, obj2);

7 - Lodash _.assignIn(object, [sources]): also named as _.extend:

const result = {};

_.assignIn(result, obj1, obj2);

8 - Lodash _.merge(object, [sources]):

const result = _.merge(obj1, obj2);

There are a couple of important differences between lodash's merge function and Object.assign:

1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign only merges the first level. For instance:

_.isEqual(_.merge({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
}), {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // true

BUT:

const result = Object.assign({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
});
_.isEqual(result, {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // false
// AND
_.isEqual(result, {
  x: {
    y: {
      key2: 'value2',
    },
  },
}); // true

2- Another difference has to do with how Object.assign and _.merge interpret the undefined value:

_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false

BUT:

_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true

Update 1:

When using for in loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype or even Object.prototype. To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key) to mke sure the key is actually part of the object you are iterating over.


Update 2:

I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.


Update 3:
I added the difference between Object.assign and _.merge.

2 of 6
15

WORKING FIDDLE

Simplest Way with Jquery -

var finalObj = $.extend(obj1, obj2);

Without Jquery -

var finalobj={};
for(var _obj in obj1) finalobj[_obj ]=obj1[_obj];
for(var _obj in obj2) finalobj[_obj ]=obj2[_obj];
🌐
GitHub
github.com › boschni › json-merger
GitHub - boschni/json-merger: Merge JSON files and objects with indicators like $import $remove $replace $merge
Merge JSON files and objects with indicators like $import $remove $replace $merge - boschni/json-merger
Starred by 50 users
Forked by 17 users
Languages   JavaScript 62.7% | TypeScript 37.3% | JavaScript 62.7% | TypeScript 37.3%
🌐
EyeHunts
tutorial.eyehunts.com › home › merge two json objects with same key javascript | example code
Merge two JSON objects with same key JavaScript | Code
November 16, 2022 - Using Nested for loop you can Merge two JSON objects with the same key JavaScript. Or You could use Map and Object.assign for merging objects
🌐
Latenode
community.latenode.com › other questions › n8n
How can I merge two JSON arrays into a single object in n8n with Node.js? - N8n - Latenode Official Community
February 3, 2025 - Combine ticket and article JSON arrays into one object in n8n using Node.js. Use this sample code: const fuseData = (ticketRec, articleList) => ({ ticket: ticketRec, articles: articleList }); module.exports = fuseData;