Reputation: 454
I have two JSON arrays with slightly different keys.
My first JSON has id
, name
and title
.
My second JSON has id
, title
, forename
, name
and company
.
So am I able to merge these two arrays, that every object has the same keys but some of them are possibly empty?
Two sample datas:
{ "id": 482136, "name": "Not a real company", "anrede": "Firma" }
{ "id": 483958, "titel": "", "anrede": "Herr", "vorname": "Muster", "name": "Mister", "firma": "gmbh", "firmaid": 1111111 }
And this should be my result:
[{ "id": 482136, "name": "Not a real company", "anrede": "Firma" ,"titel":"","vorname":"","firma":"","firmaid":""},{ "id": 483958, "titel": "", "anrede": "Herr", "vorname": "Gerry", "name": "Example", "firma": "example Company", "firmaid": 483955 }]
Thanks for your help in advance!
Upvotes: 1
Views: 255
Reputation: 35670
I have two JSON arrays with slightly different keys.
Note that these are actually objects, not arrays.
Use for … in to iterate over each property in each object, assigning an empty string to missing properties in the other object:
var j1={ "id": 482136, "name": "Not a real company", "anrede": "Firma" },
j2={ "id": 483958, "titel": "", "anrede": "Herr", "vorname": "Pascal", "name": "Ackermann", "firma": "das druckhaus beineke dickmanns gmbh", "firmaid": 483955 };
for(var key in j1) {
if(!j2[key]) j2[key]= '';
};
for(var key in j2) {
if(!j1[key]) j1[key]= '';
};
document.querySelector('pre').innerHTML= JSON.stringify(j1,null,2)+'\n'+JSON.stringify(j2,null,2);
<pre></pre>
Upvotes: 3