Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine json arrays by key, javascript

Tags:

I need to combine two json arrays, delivered by two rest services. The entries with the same "id" belong together.

json1 = [{id:1,name:'aaa'},      {id:5,name:'ccc'},      {id:3,name:'bbb'}    ];   json2 = [{id:3,parameter1:'x', parameter2:'y', parameter3:'z'},      {id:1,parameter1:'u', parameter2:'v', parameter3:'w'},      {id:5,parameter1:'q', parameter2:'w', parameter3:'e'}     ]; 

I need a combined/copied/cloned json array in javascript in the following way (my model in angular2):

json3 = [{id:3,name:'bbb',parameter1:'x', parameter2:'y',   parameter3:'z'},      {id:1,name:'aaa', parameter1:'u', parameter2:'v', parameter3:'w'},      {id:5,name:'ccc', parameter1:'q', parameter2:'w', parameter3:'e'}     ]; 

Is there a way to combine them? The parameter names are not defined exactly and it needs to work with variable parameter vectors.

I tried it with mixed for each loops. Seems to me very ugly.

like image 377
user2083142 Avatar asked Mar 09 '16 22:03

user2083142


People also ask

How do I combine two JSON objects with the same key?

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 combine two JSON arrays?

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

How can I merge two arrays in JavaScript?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How do I combine 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.


1 Answers

Two one-liners:

with lodash:

res = _(json1).concat(json2).groupBy('id').map(_.spread(_.assign)).value(); 

in ES2015:

res = json2.map(x => Object.assign(x, json1.find(y => y.id == x.id))); 
like image 153
georg Avatar answered Sep 30 '22 07:09

georg