'Check if one element exists in an array of objects
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.
Solution 1:[1]
I think this may help
let resultArray=memberships.filter(function(item) {
return item["type"] === 'member';
});
the result array holds the data of the objects that has type member
Solution 2:[2]
Use array.some()
var memberships = [{
id: 1,
type: 'guest'
},
{
id: 2,
type: 'member'
}
];
var status = memberships.some(function(el) {
return (el.type == 'member');
});
console.log(status);
Array.some()
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.
Solution 3:[3]
You can use Array#some
method:
const memberExists = memberships.some(member => member.type === 'member');
Then, if(memberExists) ...
Solution 4:[4]
You can use Array#some
var memberships = [
{
id: 1,
type: 'guest'
},
{
id: 2,
type: 'member'
}
];
console.log(memberships.some(m=>m.type==='member'));
Solution 5:[5]
You can also use find, which returns the first object if found else undefined.
let a = memberships.find(o => o.type === 'member');
if (a) {
...do something
}
Solution 6:[6]
var memberships = [
{
"Name": "family_name",
"Value": "Krishna"
},
{
"Name": "email",
"Value": "[email protected]"
}
];
let resultArray=memberships.filter(function(item) {
return item["Name"] === 'email';
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sravanthi |
Solution 2 | |
Solution 3 | |
Solution 4 | |
Solution 5 | FrankCamara |
Solution 6 |