繁体   English   中英

如何在 Node 中加入两个 JSON Array 对象

[英]How to join two JSON Array objects in Node

如何在 Node.js 中连接两个 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' }]

var 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 输出 = obj1.concat(obj2);

console.log(output);

尝试

  Object.assign(obj1, obj2);

详情请看这里

 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 }

我已经从 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 } })));

使用 ES6 可以轻松完成,

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

您可以使用jmerge包。

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

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

我只是将数组转换为字符串,用逗号粗略地连接它们,然后将结果解析为 JSON:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM