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' }]
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' }]
Share
Improve this question
edited Apr 19, 2018 at 11:05
Ratan Uday Kumar
6,4926 gold badges40 silver badges55 bronze badges
asked Dec 20, 2016 at 3:22
coriano35coriano35
1651 gold badge3 silver badges10 bronze badges
3
- Array.prototype.concat ? – Taplar Commented Dec 20, 2016 at 3:25
- 1 stackoverflow.com/questions/14974864/… – User Commented Dec 20, 2016 at 3:52
- Does this answer your question? Merge two json/javascript arrays in to one array – Vega Commented Jun 10, 2020 at 16:04
7 Answers
Reset to default 10var output = obj1.concat(obj2);
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);
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 }
It can be done easily using ES6,
const output = [...obj1, ...obj2];
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 } })));
you can use jmerge package.
npm i jmerge
const jm = require('jmerge')
jm(obj1,obj2,obj3,...) //merging json data
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)
)