Is the entire JavaScript literal object distinct from each other

I have it:

var g = [{a:'a'},{a:'2'},{a:'3'}] var c = [{a:'4'},{a:'2'},{a:'5'}] 

The following statement:

 g[1] == c[1] 

Returns false even if the objects look the same. Is there any way to compare them literally so that it returns me true instead of false?

+4
source share
4 answers

You can encode them as JSON:

 JSON.stringify(g[1]) == JSON.stringify(c[1]) 

You may also be interested in answers to this related question about identifying duplicate Javascript objects .

For a more complex version, you can look at the annotated source code for the Underscore _.isEqual() function (or just use the library).

+6
source

The == operator checks referential equality. The only way to do what you want is to test for equality in parts of objects.

This should work:

 function memberwiseEqual(a, b) { if(a instanceof Object && b instanceof Object) { for(key in a) if(memberwiseEqual(a[key], b[key])) return true; return false; } else return a == b; } 

Be careful with such cases:

 var a = {}; a.inner = a; //recursive structure! 
+1
source

here you are comparing the link in memory, not its value, try this and you will get the truth:

 g[1]['a'] === c[1]['a'] 
0
source

In JavaScript variables, which are objects (including arrays), they actually refer to the collection. Therefore, when you write var x = { a: 2 } and var y = { a: 2 } , then x and y become references to two different objects. Therefore, x will not be equal to y . But, if you did y = x , then they are (because they will have the same link). But if you change any object, then the other will also be changed.

So, when dealing with objects and arrays by saying == , you check to see if these two links are the same. In this case, this is not so.

0
source

All Articles