2

The problem is that the following makes logically no sense to me, maybe anyone could explain (explanation what JSON.parse/JSON.stringify EXACTLY does would be appreciated too):

var hello = {norsk: "hei"}, parsedHello = JSON.parse(JSON.stringify(hello));
hello === parsedHello // false
hello == parsedHello // false
typeof(hello) // "object"
typeof(parsedHello) // "object"
hello.norsk === parsedHello.norsk // true
Johnny
  • 161
  • 3
  • 11

5 Answers5

5

Objects in JS are compared by reference and since you're creating brand new object - they will not be equal.

You can compare them by stringifying them:

JSON.stringify(hello) === JSON.stringify(parsedHello)
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
  • 1
    This will work in this case, but be careful using this method in general. If the properties are out of order in the string, the two strings will not be equal even if the objects have exactly the same properties and values. – James Montagne Sep 11 '13 at 20:25
  • @JamesMontagne Agreed, the example here is just to show difference in strings and object comparasing. – Yuriy Galanter Sep 11 '13 at 20:26
2

You have two separate objects which happen to contain the same properties/data. They are not equal because they are not the same object.

In the same way:

var a = {norsk: "hei"};
var b = {norsk: "hei"};

a == b; // false

http://jsfiddle.net/AMHbM/

James Montagne
  • 77,516
  • 14
  • 110
  • 130
0

Two Objects in Javascript are not equal. I recommend using underscore's isEqual method to compare Objects. You can find it in Underscore's GitHub repo https://github.com/jashkenas/underscore/blob/master/underscore.js and only use this specific method if you do not need anything more from this library.

Jakub Kotrs
  • 5,823
  • 1
  • 14
  • 30
0

hello and parsedHello point to two separate objects. You're comparing references and so those will not be equal. == and === with objects will not do a "deep equals"; it only compares references.

See here for more information about comparing JavaScript objects.

Community
  • 1
  • 1
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
0

he confusion here is that you are comparing two objects for equality, but even though the data they represent is the same, they are different instances.

comparing the property norsk gives you the expected result because that refers to a string, and JavaScript compares strings by their values, which in this case are the same.

Unfortunately, comparing complex objects in the way you wanted above is a complex thing called structural equality and there's no easy way to do that out of the box.

Robert Byrne
  • 562
  • 2
  • 13