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?

1
  • 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 Commented Mar 11, 2015 at 10:44

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

2 Comments

JSON.stringify({a:1,b:1}) !== JSON.stringify({b:1,a:1}) Comparing objects using JSON.stringify is a bad idea.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.