Alisha Sharma
Alisha Sharma

Reputation: 149

How can we compare existing data of 2 objects of available keys only in js

I have 2 objects a and b i want to compare only data of objects of same keys

var a = {name1:'alisha',age:18,subject:{main:'javascript',major:'maths'}};
var b = {name1:'alisha',age:'18'};

 function compareData(a,b){
  return JSON.stringify(a) == JSON.stringify(b); 
 }

 console.log(compareData(a,b))

This is comparing all the keys but i want to compare only available data of available keys how can I do this

Upvotes: 0

Views: 54

Answers (2)

Paul
Paul

Reputation: 141935

You can use this for shallow comparison:

// Returns true if the values are equal (shallow)
// for all properties that both objects have
function compareData(a,b){
  return Object.keys(a).filter( k => k in b ).every( k => a[k] === b[k] );
}

It will return false for your objects because one has a number for age and the other has a string. It will return true for these objects:

var a = {name1:'alisha',age:18,subject:{main:'javascript',major:'maths'}};
var b = {name1:'alisha',age:18};

Example:

console.log( compareData( {}, {age: 5} ) ); // true (no shared properties)
console.log( compareData( {age: 5}, {age: 5} ) ); // true (equal shared properties)
console.log( compareData( {age: 4}, {age: 5} ) ); // false

var a = {name1:'alisha',age:18,subject:{main:'javascript',major:'maths'}};
var b = {name1:'alisha',age:18};

console.log( compareData( a, b ) ); // true

function compareData(a,b){
  return Object.keys(a).filter( k => k in b ).every( k => a[k] === b[k] );
}

Upvotes: 2

Antony
Antony

Reputation: 1273

Looping through the first item keys and checking if:
1. They exist
2. The value is the same

Seems to work:

var a = { name1:'alisha', age:18,subject:{main:'javascript',major:'maths'}};
var b = { name:'alisha', age: 19 };

function areTheSame(a,b){
  // fat arrow function returns true if any element has a difference
  return !Object.keys(a).some(key => {
    if(b.hasOwnProperty(key)){
      return a[key] !== b[key];
    }
    return false;
  });
}

console.log(areTheSame(a,b))

Upvotes: 1

Related Questions