There isn't really a simple "one answer fits all" solution to this, especially as the parameters of your question are quite broad. For example, what would you consider equality? Strict? Loose? Equality of only own enumerable properties, or of all properties?
I would recommend steering clear of using JSON.stringify
as 1) it is a fairly costly operation to serialise an object, especially if performing frequently, and 2) it transforms values in potentially dangerous ways for comparison sake (e.g. JSON.stringify(NaN) === JSON.stringify(null) //=> true
).
You should use a library implementation such as lodash's isEqual
, and save yourself the pain of reinventing the wheel.
However for the sake of completeness, and to give you an idea of a simple, naive approach, you could loop over each property of your object ExpectedObject
and check for equality with the equivalent property in the object ActualObject
, like so:
function isEqual (ExpectedObject, ActualObject) {
// if the ExpectedObject has a different number of
// keys than ActualObje, it is not equal
if (Object.keys(ExpectedObject).length !== Object.keys(ActualObject).length) {
return false
}
for (const key in ExpectedObject) {
// if ActualObject does not have a property that is
// on ExpectedObject, it is not equal
if (!(key in ActualObject)) {
return false
}
// if a property's value on ActualObject is not equal
// with a strict comparison, to the equivalent property
// on ExpectedObject, it is not equal
if (ActualObject[key] !== ExpectedObject[key]) {
return false
}
}
return true
}
console.log(isEqual({ a:1 }, { a: 1 })) //=> true
console.log(isEqual({ a:1 }, { a: "1" })) //=> false
console.log(isEqual({ a:1 }, { a: 1, b: 2 })) //=> false
Obviously you would need to introduce type-checking so that you know you're dealing with objects to begin with, but there's a basic idea for you to think about.