在JavaScript中合并2个json

时间:2018-10-05 17:45:51

标签: javascript json

所以我有2个具有相同参数的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}]

2 个答案:

答案 0 :(得分:3)

您可以使用Object.assign()

(function(){a = 3+2;})();

进一步了解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]));

答案 1 :(得分:2)

一种干净的方法是使用对象传播运算符。对象散布运算符在对象文字中的作用是将所有旧值复制到新创建的对象中。

示例:

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)

注意:

这是一种相对较新的语法ES7,您必须转换代码(使用babel)才能完全兼容浏览器。