When attempting to compare two different instances of objects, they will never be equal.
To enable deep comparison, you can convert the objects to primitive strings using JSON.stringify
and then utilize Array.includes
. As highlighted by ttulka, this method only works if the object being searched has properties in the same order as the object being sought in the array.
const array = [{ name: 'John', age: 33 }];
const newName = {
name: 'John',
age: 33
};
if (array.map(obj => JSON.stringify(obj)).includes(JSON.stringify(newName))) {
console.log(newName.name + ' exists');
} else {
console.log('name does not exist');
}
Referencing the Array#includes
polyfill on MDN reveals that the comparison is based on the strict equality operator ===
:
function sameValueZero(x, y) {
return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}
// 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(valueToFind, elementK) is true, return true.
if (sameValueZero(o[k], valueToFind)) {
return true;
}
// c. Increase k by 1.
k++;
}
Therefore, comparing two separate object literals using ===
will result in inequality:
console.log({name :"John"} === {name :"John"});
In contrast, primitive strings are considered equal when compared with ===
:
console.log('{name:"John"}' === '{name:"John"}');
However, the same principle does not apply to String objects:
console.log(new String('{name:"John"}') === new String('{name:"John"}'));