Is it fine to use JSON.stringify for deep comparisons and cloning?

MaiaVictor picture MaiaVictor · Mar 13, 2013 · Viewed 10.8k times · Source

After attempting several implementations for deep comparison and copying for JSON-serializable objects, I've noticed the fastest often are just:

function deep_clone(a){
   return JSON.parse(JSON.stringify(a));
};
function is_equal(a,b){
    return JSON.stringify(a) === JSON.stringify(b);
};

I feel like this is cheating, though. Like I'll find some problem that will annoy me on future. Is it fine to use those?

Answer

dstreit picture dstreit · Sep 27, 2014

JavaScript does not guarantee the order of keys.

If they are entered in the same order, this approach would work most of the time, but it would not be reliable.

Also, it would return false for objects that were deeply equal, but whose keys were entered in a different order:

JSON.stringify({ a: 1, b: 2}) === "{"a":1,"b":2}"

JSON.stringify({ b: 2, a: 1}) === "{"b":2,"a":1}"