Skip to content
Advertisement

Javascript: Using `.includes` to find if an array of objects contains a specific object

I am a bit new to javascript ES6, and I am having difficulty understanding why the below is not functioning as expected:

let check = [{name: 'trent'},{name: 'jason'}].includes({name: 'trent'}); 
// expect true - returns false

Thanks!

Advertisement

Answer

includes essentially checks if any element === the element you’re searching for. In case of objects, === means literally the same object, as in the same reference (same place in memory), not the same shape.

var a1 = { name: 'a' }
var a2 = { name: 'a' }

console.log(a1 === a2) // false because they are not the same object in memory even if they have the same data

But if you search for an object that is actually in the array it works:

var a1 = { name: 'a' }
var a2 = { name: 'a' }
var array = [a1, a2]

console.log(array.includes(a1)) // true because the object pointed to by a1 is included in this array 
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement