Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}]
like image 596
sunny Avatar asked Oct 05 '18 17:10

sunny


People also ask

How do I merge two JSON files in JavaScript?

Use concat() for arrays Assuming that you would like to merge two JSON arrays like below: var json1 = [{id:1, name: 'xxx' ...}] var json2 = [{id:2, name: 'xyz' ...}]

How do I merge two JSON objects?

JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java.

How do I combine two JSON arrays?

We can merge two JSON arrays using the addAll() method (inherited from interface java.

How do I concatenate in JSON?

To concatenate two JSON objects with JavaScript, we can use the object spread operator. const obj = { ... sourceObj1, ... sourceObj2 };


1 Answers

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)
like image 177
Mohamed Tajjiou Avatar answered Nov 15 '22 05:11

Mohamed Tajjiou