comparing two objects does not give correct results

- 1 answer

Ad

i am trying to compare two objects. The ages are different but still says they are same.. here is my code

var personA =
    {
        name: "Josh Kloss",
        age: 33
    }
var personmB =
{
    name: 'Josh Kloss',
    age: 43
}

function compareTwoPeople(a, b) {

    var person1 = Object.keys(a);
    var person2 = Object.keys(b);
    if (person1.length !== person2.length) {
        console.log("They are not same");
    }
    else {
        for (var i = 0; i < person1.length; i++) {
            if (person1[i] === person2[i]) {
                console.log("They are  same");
            }
        }
    }

}

compareTwoPeople(personA, personmB);

How can i compare these two object... Thanks.

Ad

Answer

Ad

Close, just need to tidy up the comparison a little bit to get at the object value using the key and the iterator.

var personA =
    {
        name: "Josh Kloss",
        age: 33
    };
var personB =
{
    name: 'Josh Kloss',
    age: 43
};

function compare(a, b) {
  var aKeys = Object.keys(a),
      bKeys = Object.keys(b);

  if(aKeys.length != bKeys.length) return false;

  for(var i = 0; i < aKeys.length; i++) {
    if(a[aKeys[i]] != b[bKeys[i]]) return false;
  }

  return true;

}

compare(personA, personB);
Ad
source: stackoverflow.com
Ad