coriano35
coriano35

Reputation: 165

How to join two JSON Array objects in Node

How to join two JSON Array objects in Node.

I want to join obj1 + obj2 so I can get the new JSON object:

obj1 = [ { t: 1, d: 'AAA', v: 'yes' },
         { t: 2, d: 'BBB', v: 'yes' }]

obj2 = [ { t: 3, d: 'CCC', v: 'yes' },
        { t: 4, d: 'DDD', v: 'yes' }]


output = [ { t: 1, d: 'AAA', v: 'yes' },
           { t: 2, d: 'BBB', v: 'yes' },
           { t: 3, d: 'CCC', v: 'yes' },
           { t: 4, d: 'DDD', v: 'yes' }]

Upvotes: 5

Views: 24890

Answers (7)

Amit Verma
Amit Verma

Reputation: 21

It can be done easily using ES6,

const output = [...obj1, ...obj2];

Upvotes: 2

Anurag Agarwal
Anurag Agarwal

Reputation: 107

I simply convert the arrays to strings, join them crudely with a comma, and then parse the result to JSON:

newJson=JSON.parse(
    JSON.stringify(copyJsonObj).substring(0,JSON.stringify(copyJsonObj).length-1) +
    ',' + 
    JSON.stringify(jsonObj).substring(1)
)

Upvotes: -2

Tegar Santosa
Tegar Santosa

Reputation: 57

you can use jmerge package.

npm i jmerge
const jm = require('jmerge')

jm(obj1,obj2,obj3,...) //merging json data

Upvotes: -1

coriano35
coriano35

Reputation: 165

i already got an answer from the link provided by Pravin

var merge = function() {
var destination = {},
    sources = [].slice.call( arguments, 0 );
sources.forEach(function( source ) {
    var prop;
    for ( prop in source ) {
        if ( prop in destination && Array.isArray( destination[ prop ] ) ) {

            // Concat Arrays
            destination[ prop ] = destination[ prop ].concat( source[ prop ] );

        } else if ( prop in destination && typeof destination[ prop ] === "object" ) {

            // Merge Objects
            destination[ prop ] = merge( destination[ prop ], source[ prop ] );

        } else {

            // Set new values
            destination[ prop ] = source[ prop ];

        }
    }
});
return destination;
};

console.log(JSON.stringify(merge({ a: { b: 1, c: 2 } }, { a: { b: 3, d: 4 } })));

Upvotes: 0

Vaghani Janak
Vaghani Janak

Reputation: 611

obj1 = [ { t: 1, d: 'AAA', v: 'yes' },
         { t: 2, d: 'BBB', v: 'yes' }]

obj2 = [ { t: 3, d: 'CCC', v: 'yes' },
        { t: 4, d: 'DDD', v: 'yes' }]

var output = obj1.concat(obj2);

console.log(output);

Upvotes: 8

therobinkim
therobinkim

Reputation: 2568

var output = obj1.concat(obj2);

Upvotes: 10

User
User

Reputation: 1363

try

  Object.assign(obj1, obj2);

For Details check Here

 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 }

Upvotes: 6

Related Questions