简体   繁体   English

在JavaScript中合并2个json

[英]merge 2 json in javascript

So I have 2 json which has one same parameter. 所以我有2个具有相同参数的json。 based on this one parameter I want to merge these two json into single json. 基于这一参数,我想将这两个json合并为单个json。

json 1 = [{"serverid":65,"name":"Apple"},{"serverid":98,"name":"Mac"}]

json 2 = [{"serverid":98,"count":9},{"serverid":65,"count":2}]

resultant json = [{"serverid":65,"name":"Apple","count":2},{"serverid":98,"name":"Mac","count":9}]

You can use Object.assign() 您可以使用Object.assign()

const a = [{"serverid":65,"name":"Apple"},{"serverid":98,"name":"Mac"}];
const b = [{"serverid":65,"count":2},{"serverid":98,"count":9}];
const c = a.map((obj, index) => Object.assign(obj, b[index]));

to learn more about Object.assign() 了解有关Object.assign()的更多信息

 const a = [{"serverid":65,"name":"Apple"},{"serverid":98,"name":"Mac"}]; const b = [{"serverid":65,"count":2},{"serverid":98,"count":9}]; const c = a.map((obj, index) => Object.assign(obj, b[index])); console.log(c) 

A clean way of doing is is using the object spread operator. 一种干净的方法是使用对象传播运算符。 What the object spread operator does in an object literal is copying all old values into the newly created object. 对象散布运算符在对象文字中所做的就是将所有旧值复制到新创建的对象中。

Example: 例:

 const json1 = [{"serverid": 65,"name": "Apple"},{"serverid":98,"name":"Mac"}] const json2 = [{"serverid":65,"count":2},{"serverid":98,"count":9}] const newArr = [] for (let i = 0; i < json1.length; i++) { const obj = { ...json1[i], ...json2[i] } newArr.push(obj); } console.log(newArr) 

Caveat: 警告:

This is relatively new syntax ES7 and you have to transpile the code (using eg babel) in order to have full browser compatibility. 这是相对较新的ES7语法,您必须转换代码(使用例如babel)才能具有完全的浏览器兼容性。

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

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