r3plica r3plica - 4 months ago 49x
AngularJS Question

JSON.stringify and angular.toJson not working as expected

So I have to objects:

var productCopy = {
"light": true,
"new": true,
"available": false

var model = {
"light": true,
"new": true,
"available": false

I need to compare both, so I did this:

// Create our 2 strings
var productCopyString = JSON.stringify(productCopy);
var modelString = JSON.stringify(model);

and then I did this:

return modelString !== productCopyString;

but it wasn't working. So I did a console.log like this:

console.log('productCopy', productCopyString);
console.log('model', modelString);
console.log('are they different', modelString !== productCopyString)

and that returned:

productCopy {"light":true,"new":true,"available":false}

model {"light":true,"new":true,"available":false}

are they different false

which was strange, so I did this:

var productCopyString = angular.toJson(productCopy);
var modelString = angular.toJson(model);

And I got the same result.

Does anyone know why?


In Javascript, two strings are equal === if they have the same data.

Ex: '{"light":true,"new":true,"available":false}' === '{"light":true,"new":true,"available":false}'

Note: In other languages like Java, two strings are equal == is they refer to the same instance. In that case, two strings with same data would not be ==.