如何在Node中连接两个JSON Array对象

cor*_*o35 7 javascript json node.js

如何在Node中连接两个JSON Array对象.

我想加入obj1 + obj2所以我可以获得新的JSON对象:

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' }]
Run Code Online (Sandbox Code Playgroud)

the*_*kim 9

var output = obj1.concat(obj2);


Pra*_*vin 7

尝试

  Object.assign(obj1, obj2);
Run Code Online (Sandbox Code Playgroud)

详情请点击此处

 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 }
Run Code Online (Sandbox Code Playgroud)


Vag*_*nak 7

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' }]
Run Code Online (Sandbox Code Playgroud)

var output = obj1.concat(obj2);

console.log(output);
Run Code Online (Sandbox Code Playgroud)


cor*_*o35 0

我已经从 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 } })));
Run Code Online (Sandbox Code Playgroud)