Why you have to stop compare objects with JSON.stringify


javascript

This is my IMHO. I have seen this in many projects and this can create a potential issue

Assume, you have two objects:

const x = {b:1, c: 2}
const y = {b:1, c:2}

They have the same keys and the same values for appropriate keys. If you try to compare these objects with JSON.stringify it will give you true:

const x = {b:1, c: 2}
const y = {b:1, c:2}

JSON.stringify(x) === JSON.stringify(y) // true

All is good and our task was resolved, but what will be in the following situation:

const x = {b:1, c: 2}
const y = {c:2, b:1}

These objects have the same keys and values as well, but each object has another order of keys:

const x = {b:1, c: 2}
const y = {c:2, b:1}

JSON.stringify(x) === JSON.stringify(y) // false

As you see this piece of code can create a potential problem for the logic.

comments powered by Disqus