Combine or merge JSON on node.js without jQuery

node js merge array of objects
concatenate two json objects node js
merge two json objects angular 6
merge two json objects python
merge two json objects javascript
javascript merge key value pairs
javascript merge objects
javascript merge objects with same key

I have multiple JSON like those

var object1 = {name: "John"};
var object2 = {location: "San Jose"};

They are not nesting or anything like that. Just basically different fields. I need to combine them into one single JSON in node.js like this:

{name: "John", location: "San Jose"}

I can use jQuery just fine. Here is a working example in the browser:

But if I do this in node.js, I don't want to load jQuery (which is a bit over use, plus node.js' jQuery doesn't work on my Windows machine).

So is there a simple way to do things similar to $.extend() without jQuery?

A normal loop?

function extend(target) {
    var sources = [], 1);
    sources.forEach(function (source) {
        for (var prop in source) {
            target[prop] = source[prop];
    return target;

var object3 = extend({}, object1, object2);

That's a basic starting point. You may want to add things like a hasOwnProperty check, or add some logic to handle the case where multiple source objects have a property with the same identifier.

Here's a working example.

Side note: what you are referring to as "JSON" are actually normal JavaScript objects. JSON is simply a text format that shares some syntax with JavaScript.

javascript, A normal loop? function extend(target) { var sources = [], 1); sources.forEach(function (source) { for (var prop in source) { target[prop]  The below code will help you to merge two JSON object which has nested objects. function mergeJSON(source1,source2){ /* * Properties from the Souce1 object will be copied to Source2 Object. * Note: This method will return a new merged object, Source1 and Source2 original values will not be replaced.

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

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.

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.

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 Post · Node.js is everywhere · MongoDB root user · Combine JavaScript and CSS · Inline Small JavaScript How do I debug Nodejs applications? Home » Nodejs » Combine or merge JSON on node.js without jQuery Combine or merge JSON on node.js without jQuery Posted by: admin November 7, 2017 Leave a comment

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:

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;
        origin[keys[i]] = add[keys[i]];
    return origin;

How to add two JSON objects into one object JavaScript, Corey Butler, Wrote JS Software used by 2M+ people. To combine both objects into one, we can create a parent object, How can I load data from a JSON file into a variable in JavaScript without using Ajax? Ma Ni Sh, nodejs developer Source: Javascript Merge Objects Code Example. Everyday one topic to go as master in Future. Book contains technical topics of computer software development. Such as MySQL, Core Java, HTML, CSS and JQuery and More.

Underscore's extend is the easiest and quickest way to achieve this, like James commented.

Here's an example using underscore:

var _ = require('underscore'), // npm install underscore to install
  object1 = {name: "John"},
  object2 = {location: "San Jose"};

var target = _.extend(object1, object2);

object 1 will get the properties of object2 and be returned and assigned to target. You could do it like this as well, depending on whether you mind object1 being modified:

var target = {};
_.extend(target, object1, object2);

jQuery.extend(), Description: Merge the contents of two or more objects together into the first object. new MyCustomObject(args) , or built-in JavaScript types such as Date or RegExp, are not On a deep extend, Object and Array are extended, but object wrappers on primitive Merge defaults and options, without modifying the defaults. Otherwise for objects you can check How can I merge properties of two JavaScript objects dynamically? For reference: var array = [] // this is array var theObject = {} // json object if you want to merge them into one object try: jQuery.extend(object1[0], object2[2]);

Use merge.

$ npm install merge

Sample code:

var merge = require('merge'), // npm install -g merge
    original, cloned;


    merge({ one: 'hello' }, { two: 'world' })

); // {"one": "hello", "two": "world"}

original = { x: { y: 1 } };

cloned = merge(true, original);


console.log(original.x.y, cloned.x.y); // 1, 2

jQuery.merge(), Prior to jQuery 1.4, the arguments should be true Javascript Array objects; use $.​makeArray if they are not. Examples: Merges two arrays, altering the first argument  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:

.map(), As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to 1. 2. 3. 4. 5. 6. $( ":checkbox" ) .map(function() {. return;. }) .get() .join(); If the function returns null or undefined , no element will be inserted. <script src=""></​script>. The first array-like object to merge, the elements of second added. The second array-like object to merge into the first, unaltered. The $.merge() operation forms an array that contains all elements from the two arrays. The orders of items in the arrays are preserved, with items from the second array appended.

Merge javascript JSON's · GitHub, Now we know how to parse the query string, and in the previous chapter we learned how to make Node.js behave as a file server. Let us combine the two, and  Description: Merge the contents of two or more objects together into the first object. An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported.

Node.js URL Module, Merge javascript JSON's. GitHub Gist: instantly share code, notes, and snippets.

  • If you're doing various things like this, you might want to consider using Underscore, which is available as a Node module.
  • npm install extend, Port of jQuery.extend for Node.js.
  • FYI Object.assign does this, but unfortunately it's not currently supported. Hopefully someday soon!…
  • That's not JSON, you're just creating standard JS objects using literal notation. (E.g. in JSON keys must be strings). And when you're 'combining' those object it has zero to do with JSON.
  • I use this function to merge two json. But the reultant json is prefexed with '0'. Example 0 : {kye : value}. Please help me how do i prefix with my own string instead of '0'?
  • Down voted cause this is one of the cases where people, especially newbies, should be directed to tested libraries.
  • +1 To anyone coming here looking for a native browser alternative, note this is an ES6 feature and as such not well supported yet.
  • Adding to Boaz comment, in the Mozilla link for Object.assign above, you can find a polyfill that works just fine in a browser.
  • Call it with an empty first argument to avoid accidentally mangling your objects: var obj = Object.assign({}, o1, o2, o3)
  • The underscore in _extend represents a private method, meaning it is not intended for public use. Not only is this method undocumented, but the implementation could change in any revision, affecting your project.
  • As @jimbojw mentioned in a comment on the linked answer, Isaacs says "You can go ahead and use util._extends() … It's not going anywhere any time soon". There is further discussion in that thread. If you are worried, read through and make a decision for your project.
  • npm install util-extend