0

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.

rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38

2 Answers2

0

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');
}
Ishwar Patil
  • 1,671
  • 3
  • 11
  • 19
0

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)
Arman Charan
  • 5,669
  • 2
  • 22
  • 32