测试值是否存在于对象数组中
Test whether value exists within array of objects
我有一个对象数组,我想测试它以确定具有特定值的 属性 是否存在(至少出现一次)并将其 return 为布尔值来表示结果。我正在使用 Ramda 库,并一直在试验 has
函数来尝试实现这一点,但这只是 return 一个布尔值,表示实际 属性 是否存在,而不是它各自的值.
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'
},
];
检查 sport: 'rugby'
的对象数组应该 return true
和 sport: 'tennis'
应该 return false。
非常感谢任何帮助,谢谢。
你可以试试这个功能:
function myFind(data, key, value) {
return data.some(function(obj){
return key in obj && obj[key] == value;
});
}
参考:Array.some()
如果您正在寻找 Ramda 解决方案,这会很好:
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
检查 属性 值是否匹配任意谓词。
我有一个对象数组,我想测试它以确定具有特定值的 属性 是否存在(至少出现一次)并将其 return 为布尔值来表示结果。我正在使用 Ramda 库,并一直在试验 has
函数来尝试实现这一点,但这只是 return 一个布尔值,表示实际 属性 是否存在,而不是它各自的值.
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'
},
];
检查 sport: 'rugby'
的对象数组应该 return true
和 sport: 'tennis'
应该 return false。
非常感谢任何帮助,谢谢。
你可以试试这个功能:
function myFind(data, key, value) {
return data.some(function(obj){
return key in obj && obj[key] == value;
});
}
参考:Array.some()
如果您正在寻找 Ramda 解决方案,这会很好:
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
检查 属性 值是否匹配任意谓词。