This is because you are trying to compare two different instances of objects which will never be equal.
But if you convert the objects to primitive strings by doing JSON.stringify
you can then use Array.includes
for deep comparison. As ttulka pointed out, this will only work if the object to be searched has the properties in the same order as the object to find 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');
}
If you look into the Array#includes
polyfill in MDN, you would see that the comparison happens using 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++;
}
So when you compare two different object literals using ===
they won't be equal:
console.log({name :"John"} === {name :"John"});
But primitive strings on the other hand are equal if you compare them with ===
:
console.log('{name:"John"}' === '{name:"John"}');
But the same is not true for String objects:
console.log(new String('{name:"John"}') === new String('{name:"John"}'));