Compare two objects if any one of the object not having key pair.
var itemA= [{"name": "saran", "address":"chennai"},
{"name": "elango", "address":"chennai"},
{"name": "kala", "address": "chennai"}];
var itemB= [{"name": "saran", "address":"chennai"},
{"name": "elango", "address":"chennai"}];
I wrote following code to compare two objects,
function compareJSON(itemA, itemB) {
for(var prop in itemA) {
if(itemB.hasOwnProperty(prop)) {
switch(typeof(itemA[prop])) {
case "object":
compareJSON(itemA[prop], itemB[prop]);
break;
default:
if(itemA[prop] !== itemB[prop]) {
}
break;
}
}
}
}
Here i have two object i need to compare above two object. I used to for loop for compare two object with hasOwnProperty() method. the prop is having itemA of object it's checked with itemB object if it's different i took itemA object.
Here problem is not able compare itemA 3rd value not able to compare because in itemB does not have a 3rd element.
Check this out.
If not equal, you can write your custom modifications/logic.
var itemA= [{"name": "saran", "address":"chennai"}, {"name": "elango", "address":"chennai"}, {"name": "kala", "address": "chennai"}]; var itemB= [{"name": "saran", "address":"chennai"}, {"name": "elango", "address":"chennai"}]; let keysA = Object.keys(itemA); let keysB = Object.keys(itemB); if(keysA.length === keysB.length) { let flag = true; keysA.map( a => { if(!keysB.includes(a)) { flag = false; } }) flag ? alert('Equal') : alert('Not equal'); } else { alert('Not equal'); }
Array.prototype.reduce()
, JSON.stringify()
and Array.prototype.includes()
can be combined to find the differences between Arrays
A
and B
.
// A. const A = [ {name: "saran", address:"chennai"}, {name: "elango", address:"chennai"}, {name: "kala", address: "chennai"} ] // B. const B = [ {name: "saran", address:"chennai"}, {name: "elango", address:"chennai"} ] // Differences. const differences = A.reduce((differences, object) => (!JSON.stringify(B).includes(JSON.stringify(object)) && [...differences, object] || differences), []) // Log. console.log(differences)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.