我是JavaScript新手并试图找到两个JSON对象之间的区别。 JSON对象的结构及其数据如下所示。我在线获得了一个适用于普通JSON对象的代码,但由于这也有一个数据数组,我认为它不起作用。我尝试了不同的东西,但没有结果。如果你有这方面的指针,将不胜感激。感谢。
JSON对象1(obj1): {id: 1, details: Array[2], profession: "Business"}
{
"id": "1",
"details": [{
"name": "Peter",
"address": "Arizona",
"phone": 9900998899
},
{
"name": "Jam",
"address": "Kentucky",
"phone": 56034033343
}
],
"profession": "Business"
}
JSON对象2(obj2): {id: 2, details: Array[2], profession: "Business"}
{
"id": "2",
"details": [{
"name": "Peter",
"address": "Arizona",
"phone": 9900998899
},
{
"name": "David",
"address": "Boston",
"phone": 434323434
}
],
"profession": "Business"
}
解决方案:
compare(obj1, obj2) {
var result = {};
for (key in obj1) {
if (obj2[key] != obj1[key]) {
result[key] = obj2[key];
}
if (typeof obj2[key] === '[object Array]' && typeof obj1[key] === '[object Array]') {
result[key] = compare(obj1[key], obj2[key]);
}
if (typeof obj2[key] === 'object' && typeof obj1[key] === 'object') {
result[key] = compare(obj1[key], obj2[key]);
}
}
console.log(result);
}
结果:
Object {0: undefined, 1: undefined}
Object {id: "2", pingedAddresses: undefined, type: "Business"}
预期:
{
"id": "2",
"details": [{
"name": "David",
"address": "Boston",
"phone": 434323434
}]
}
答案 0 :(得分:5)
您可以尝试以下简单比较:
注意:此答案假定结构完全相同。您可以将此作为参考,并使其在结构不同的情况下更通用。
要考虑的要点:
o1.details
有2个条目,o2.details
有5个条目。
function getDifference(o1, o2) {
var diff = {};
var tmp = null;
if (JSON.stringify(o1) === JSON.stringify(o2)) return;
for (var k in o1) {
if (Array.isArray(o1[k]) && Array.isArray(o2[k])) {
tmp = o1[k].reduce(function(p, c, i) {
var _t = getDifference(c, o2[k][i]);
if (_t)
p.push(_t);
return p;
}, []);
if (Object.keys(tmp).length > 0)
diff[k] = tmp;
} else if (typeof(o1[k]) === "object" && typeof(o2[k]) === "object") {
tmp = getDifference(o1[k], o2[k]);
if (tmp && Object.keys(tmp) > 0)
diff[k] = tmp;
} else if (o1[k] !== o2[k]) {
diff[k] = o2[k]
}
}
return diff;
}
var o1={id:"1",details:[{name:"Peter",address:"Arizona",phone:9900998899},{name:"Jam",address:"Kentucky",phone:56034033343}],profession:"Business"},
o2={id:"2",details:[{name:"Peter",address:"Arizona",phone:9900998899},{name:"David",address:"Boston",phone:434323434}],profession:"Business"};
var d = getDifference(o1, o2)
console.log(d)
我写了一个答案to detect changes in objects。你甚至可以参考这个。
答案 1 :(得分:0)
您需要在第一个对象上运行for循环,并检查第二个对象是否包含它。然后将其保存到新的第三个对象:
var obj3={};
for (var key in obj1)
{
!obj2.hasOwnProperty(key) && obj3[key]=obj[key];
}