Can anyone help me to understand the difference in obj1 and obj2 created in two ways in JavaScript? They look the same in the console.
var obj1 = { 'name': 'blue', 'shade': 'dark'};
var obj2 = JSON.parse('{"name":"blue","shade":"dark"}');
because
(obj1 === obj2) is false as
(obj1 == obj2) is false
while in javascript console show as
Object {name: "blue", shade: "dark"}
Object {name: "blue", shade: "dark"}
-
possible duplicate of How to determine equality for two JavaScript Objects?Getz– Getz2014年08月05日 15:14:16 +00:00Commented Aug 5, 2014 at 15:14
-
A variable that is assigned an object doesn't actually hold the value of the object, but rather a reference to it. 2 separate objects, 2 different references.Elias Van Ootegem– Elias Van Ootegem2014年08月05日 15:17:41 +00:00Commented Aug 5, 2014 at 15:17
3 Answers 3
While the objects content is the same, you have references to two separate objects, which is why == and === both fail (they check for reference not content).
Comments
As ABucin said, javascript checks for references, if you still want to check if two jsons are equal you could try using
JSON.stringify(obj1) === JSON.stringify(obj2)
or check for every key (a bit more complicated but more efficient in the case that the keys are in different orders).
Try reading this:
1 Comment
you are creating an object with obj1 and in obj2 you parsing a JSON object into an object. Since both objects are different (different reference) they are treated as different
You can learn more on this over here