Reputation: 165
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
Reputation: 21
It can be done easily using ES6,
const output = [...obj1, ...obj2];
Upvotes: 2
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
Reputation: 57
you can use jmerge package.
npm i jmerge
const jm = require('jmerge')
jm(obj1,obj2,obj3,...) //merging json data
Upvotes: -1
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
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