Here is a straightforward approach for ES6:
function shallowEquals(a, b) {
if (a === b)
return true;
if (a === null || b === null)
return false;
const ka = Object.keys(a);
const kb = Object.keys(b);
if (ka.length !== kb.length)
return false;
return ka.every(ki => a[ki] === b[ki]);
}
This code assumes that a
and b
are both objects. They may be null
, but not undefined
.
This function implements a variety of short-circuits to improve performance in common cases. Per the question, this is a shallow equals method, so it will not work properly if any values are not ===
-comparable.
If your objects might contain undefined-valued properties, then you'll also need to check that the keys themselves are the same, per the below. This is uncommon, but worth mentioning.
function shallowEqualsWithUndefinedValuedProperties(a, b) {
if (a === b)
return true;
if (a === null || b === null)
return false;
const ka = Object.keys(a);
const kb = Object.keys(b);
if (ka.length !== kb.length)
return false;
// You only need this check if your objects may contain
// undefined-valued properties, e.g., {"a":undefined}
// If your objects have many properties, then it might
// improve performance to create a Set from the contents
// of kb and test against that instead.
if (ka.some(kai => kb.indexOf(kai) === -1))
return false;
return ka.every(ki => a[ki] === b[ki]);
}
JSON.stringify(a) === JSON.stringify(b)
– JacJSON.stringify
. – Wealth