Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if two objects are the same with JavaScript?

Tags:

javascript

I need a function:

function isSame(a, b){
} 

In which, if a and b are the same, it returns true.
, I tried return a === b, but I found that [] === [] will return false.
Some results that I expect this function can gave:

isSame(3.14, 3.14);  // true  
isSame("hello", "hello"); // true  
isSame([], []); // true  
isSame([1, 2], [1, 2]); // true  
isSame({ a : 1, b : 2}, {a : 1, b : 2}); //true  
isSame([1, {a:1}], [1, {a:1}]);  //true
like image 992
wong2 Avatar asked Jul 14 '11 06:07

wong2


3 Answers

You could embed Underscore.js and use _.isEqual(obj1, obj2). The function works for arbitrary objects and uses whatever is the most efficient way to test the given objects for equality.

like image 103
ThiefMaster Avatar answered Oct 19 '22 14:10

ThiefMaster


the best way to do that is to use a JSON serializer. serialize both to string and compare the string.

like image 45
TheBrain Avatar answered Oct 19 '22 16:10

TheBrain


There are some examples, adapted from scheme, on Crockford's site. Specifically, check out:

function isEqual(s1, s2) {
    return isAtom(s1) && isAtom(s2) ? isEqan(s1, s2) :
            isAtom(s1) || isAtom(s2) ? false :
            isEqlist(s1, s2);
}

It can all be found here:

http://javascript.crockford.com/little.js

Here is a working example:

http://jsfiddle.net/FhGpd/

Update:

Just wrote some test cases based on the OP. Turns out I needed to modify the sub1 function to check <= 0 not === 0 otherwise isEqual(3.14, 3.14) blew the stack. Also, isEqual does not work for object comparison, so you are on your own there. However, if you follow the examples on Crockford's site you will see how easy and fun it is to write recursive methods that could be used to check for object equality.

like image 31
Adam Avatar answered Oct 19 '22 14:10

Adam