I have the following array of objects:
var memberships = [
{
id: 1,
type: 'guest'
},
{
id: 2,
type: 'member'
}
];
How can I verify if such an array has at least one element with type 'member'?
Note that the array can also have no elements.
Use array.some()
var memberships = [{
id: 1,
type: 'guest'
},
{
id: 2,
type: 'member'
}
];
var status = memberships.some(function(el) {
return (el.type === 'member');
});
/*
// Simplified format using arrow functions
var status = memberships.some(el => el.type === 'member')
*/
console.log(status);
Array.some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value. If such an element is found, some() immediately returns true. Otherwise, some() returns false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With