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!
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!
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
It doesn't work because objects are never the same, each object has its own reference:
Use array.prototype.some
instead:
const arr = [{name: 'trent'},{name: 'jason'}];
const obj = {name: 'trent'};
const check = arr.some(e => e.name === obj.name);
console.log(check);
includes
check if the value is present in the array, and your case the value is a reference value and is different for each declaration of a literal (even if the literal is same)
Demo
var a = {name: 'trent'};
var b = {name: 'jason'};
[a,b].includes(a); //true
Use some
instead to match the entire object:
var objToFind = JSON.stringify( {name: 'trent'} );
let check = [{name: 'trent'},{name: 'jason'}].map( s => JSON.stringify( s ) ).some( s => s == objToFind );
One of these
let check = [{name: 'trent'}, {name: 'jason'}]
.map(item => item.name)
.includes('trent');
OR
let check = !![{name: 'trent'}, {name: 'jason'}].find(({name})=> name ==='trent')
You could use Array.find() method to check if the array includes the object as "Array.includes checks for '===' in the array" which doesn't work for objects
Example solution:
let check = [{name: 'trent'},{name: 'jason'}].find(element => element.name === 'trent');
The includes()
method determines whether an array includes a certain element, returning true
or false
as appropriate. But in the way you are comparing two objects they are not equal. They should have the same reference in the memory to be equal to each other.
What you can use is something like below
var arr = [{name : "name1"}, {name : "name2"}];
var objtoFind = {name : "name1"}
var found = arr.find(function(element) {
return element.name === objtoFind.name ;
});
console.log((found ? true : false));