Reputation: 317
I have an array of objects and I would like to test it to determine whether a property with a certain value exists (at least one occurrence) and for it to return a boolean value to indicate the result. I'm using the Ramda library and have been experimenting with the has
function to try and achieve this, however this only returns a boolean on whether the actual property exists and not it's respective value.
const data = [
{
id: 10004,
name: 'Daniel',
age: 43,
sport: 'football'
},
{
id: 10005,
name: 'Tom',
age: 23,
sport: 'rugby'
},
{
id: 10006,
name: 'Lewis',
age: 32,
sport: 'football'
},
];
Checking the array of objects for sport: 'rugby'
should return true
and sport: 'tennis'
should return false.
Any help will be greatly appreciated, thanks.
Upvotes: 3
Views: 6983
Reputation: 50797
If you're looking for a Ramda solution, this would do fine:
R.filter(R.propEq('sport', 'rugby'))(data)
R.has
, as you noted, just checks whether an object has the named property. R.propIs
checks whether the property is of the given type. R.propEq
tests whether the property exists and equals a given value, and the more generic R.propSatisfies
checks whether the property value matches an arbitrary predicate.
Upvotes: 12
Reputation:
You can try this function:
function myFind(data, key, value) {
return data.some(function(obj){
return key in obj && obj[key] == value;
});
}
Reference: Array.some()
Upvotes: 2