我有两个键略有不同的 JSON 数组。
我的第一个 JSON 有 id
、name
和 title
。
我的第二个 JSON 有 id
、title
、forename
、name
和 company
。
那么我能否合并这两个数组,使每个对象都具有相同的键,但其中一些可能为空?
两个示例数据:
{ "id": 482136, "name": "Not a real company", "anrede": "Firma" }
{ "id": 483958, "titel": "", "anrede": "Herr", "vorname": "Muster", "name": "Mister", "firma": "gmbh", "firmaid": 1111111 }
这应该是我的结果:
[{ "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 }]
提前感谢您的帮助!
最佳答案
I have two JSON arrays with slightly different keys.
请注意,这些实际上是对象,而不是数组。
使用for … in遍历每个对象中的每个属性,将空字符串分配给另一个对象中缺少的属性:
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>
关于javascript - 使用不同的键合并 2 个 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32199784/