Loading ...

Compare two objects for equality

Who is online?  0 guests and 0 members
home  »  forums   »  asp.net topics   »  client side web development   » Compare two objects for equality

Compare two objects for equality

Posts under the topic: Compare two objects for equality

Posted: 7/18/2010

Lurker 170  points  Lurker
  • Joined on: 10/17/2009
  • Posts: 34

Hi, 

I have two javascript objects I want to compare them whether they are equal or not how will I do so ?


Posted: 7/26/2010

Starter 1414  points  Starter
  • Joined on: 12/1/2008
  • Posts: 66
  Answered

 

shawn said:

 

Hi, 

I have two javascript objects I want to compare them whether they are equal or not how will I do so ?

 

 

Hi Shaw,

 

Checkout this link it might help you out.

 

http://stackoverflow.com/questions/1068834/object-comparison-in-javascript

 

http://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript

 

 

Thanks,

Sumit Arora

 


Posted: 7/27/2010

Guru 16518  points  Guru
  • Joined on: 4/19/2009
  • Posts: 483
  Answered

From Definitive Guide

 

// This mixin class defines an equals() method that can compare
// simple objects for equality.
function GenericEquals() {}
GenericEquals.prototype.equals = function(that) {
    if (this == that) return true;
    
    // this and that are equal only if this has all the properties of 
    // that and doesn't have any additional properties
    // Note that we don't do deep comparison.  Property values
    // must be === to each other.  So properties that refer to objects
    // must refer to the same object, not objects that are equals()
    var propsInThat = 0;
    for(var name in that) {
        propsInThat++;
        if (this[name] !== that[name]) return false;
    }

    // Now make sure that this object doesn't have additional props
    var propsInThis = 0;
    for(name in this) propsInThis++;
    
    // If this has additional properties then they are not equal
    if (propsInThis != propsInThat) return false;

    // The two objects appear to be equal.
    return true;
}



 


Page 1 of 1 (3 items)