简体   繁体   中英

merge 2 json in javascript

So I have 2 json which has one same parameter. based on this one parameter I want to merge these two json into single 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()

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()

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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