Compare JSON objects ignoring the order of the properties in JavaScript
To compare two JSON objects we cannot use equality operators === (in case of JavaScript), == (in case of Java).
In JavaScript we primarily compare two JSON objects by converting them to their string versions using JSON.stringify
. It seems to be the most obvious and easiest choice for comparison as no external dependency is required. But there’s a problem, what if the JSON objects have same properties but in different order. The equality check would fail in this case. This is why we don’t recommend to use JSON.stringify while comparing JSON objects.
We have a few options to compare two JSON objects and ensure equality.
Lodash’s .isEqual() is our favorite pick.
var _ = require('lodash'); _.isEqual({a:1, b:2}, {b:2, a:1}); //true
fast-equals is another option which provides blazing fast equality comparisons.
import { deepEqual } from 'fast-equals'; console.log(deepEqual({a:1, b:2}, {b:2, a:1})); // true
deep-equal which is Node’s assert.deepEqual() algorithm
as a standalone module. This module is around 46 times faster than wrapping assert.deepEqual()
in a try/catch
.
var equal = require('deep-equal'); console.log(equal({a:1, b:2}, {b:2, a:1})); // true
deep-equal performs well than JSON.stringify() as tested by Matt Zeunert.

Another way written by Subash Chandran based on deep-equal-in-any-order.