This question already has an answer here:
I am trying to check if array of objects contain a specific object or object with specific property.
var mainArray = [
{name:"Yahya", age:"29"},
{name:"Ahmed", age:"19"},
{name:"Mohamed", age:"10"},
{name:"Ali", age:"32"},
{name:"Mona", age:"25"},
{name:"Shady", age:"62"},
{name:"Reem", age:"11"},
{name:"Marwa", age:"52"}
]
var myObject = {name:"Yahya", age:"29"};
function check() {
if (mainArray.indexOf(myObject) > -1) {
console.log("true")
return true;
} else {
console.log('false')
return false;
}
};
<button onClick="check()">Check</button>
here's however the object is same as one of array objects . but it's return false . I tried includes, also not working.
You can check if
some
elements of that array are the same as the object you are checking against when stringified, like so:The indexOf will try to find the object in the collection using the basic comparison mechanism. Try to run:
{name:"Yahya", age:"29"} === {name:"Yahya", age:"29"}
in javascript console and you'll get false, since these are 2 different objects, created using the same string literals.I believe you should read more info on Objects in OOP in general.
To check if a collection contains an element with the tester function provided use Array.prototype.some():
Notice that the comparison is done using "===", if you have age in your mainArray collection set as string and in myObject - as number, use "==" for age comparison instead.
If you wish to check if the array of objects contain that specific object then you can use
Array.some
You can also use
filter
method.In this case it will return an array of the matched elements. Check the length of the returned array to verify if it contains desired elementsThere is a
Array
method given byfindIndex
, we can do simply something like below