1

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?

batman
  • 3,565
  • 5
  • 20
  • 41
  • totally agree with @dfsq, only add you can compare inner primitive types (`string` and `int`) to simulate the comparation and obtain `true` if needed, ask if you need more info to achieve it – Jordi Castilla Mar 11 '15 at 10:44

3 Answers3

2

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
1

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

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
Kiba
  • 10,155
  • 6
  • 27
  • 31
0

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.

Community
  • 1
  • 1
jib
  • 40,579
  • 17
  • 100
  • 158
  • `JSON.stringify({a:1,b:1}) !== JSON.stringify({b:1,a:1})` Comparing objects using `JSON.stringify` is a bad idea. – Andreas Louv Mar 11 '15 at 22:45
  • I agree, that's why I linked to an answer which explains these limitations. I'll edit my answer to mention this, but without more context from the OP it is hard to give a general answer. – jib Mar 12 '15 at 13:32