batman
batman

Reputation: 3685

Two objects are equal, but js does say false.

I have object whose (JSON.stringify) looks like:

"{"test":[{"header":{"test":1}}]}"

and another object which looks like:

"{"test":1}"

Now if I try this:

firstObj.test[0].header == secondObj

javascript says false. Why?

Upvotes: 1

Views: 146

Answers (3)

jib
jib

Reputation: 42430

As others here point out, object comparison in JS is same-instance comparison, not value comparison. For your limited example, comparing instead the results of JSON.stringify() would seem to work, but if you cannot guarantee the order of properties (which JS does not), then that won't work either. See Object comparison in JavaScript for details. That link has a more intricate answer, but if you know the objects you're comparing then the best test of comparison is a specific one IMHO, e.g. test for the properties you care about. Objects can be anything in JS, therefore, thinking of objects as being "equal" does not make sense outside a specific context.

Upvotes: 0

Kiba
Kiba

Reputation: 10827

Javascript compares non-primitives by reference, Two references cannot be same.

var a = {};
var b = a;

then

a == b //true

Similar case for Arrays, Functions

Upvotes: 1

dfsq
dfsq

Reputation: 193261

In Javascript two objects (e.i. objects, arrays, functions - all non-primitive types) are equal only if they are the same objects, otherwise even if they look the same, have same properties and values - they are different objects and there is no way comparing them would give you true.

Upvotes: 2

Related Questions