I am new to JavaScript and trying to find the difference between two JSON Objects. The structure of the JSON object and its data is shown below. I got a code online which works for a normal JSON object but as this also has an array of data, I think it doesnt work for that. I tried different things but to no result. If you have pointers for this, it would be greatly appreciated. Thanks.
JSON Object 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 Object 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"
}
Solution:
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);
}
Result:
Object {0: undefined, 1: undefined}
Object {id: "2", pingedAddresses: undefined, type: "Business"}
Expected:
{
"id": "2",
"details": [{
"name": "David",
"address": "Boston",
"phone": 434323434
}]
}