2

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.

4

2 回答 2

11

如果您正在寻找 Ramda 解决方案,这会很好:

R.filter(R.propEq('sport', 'rugby'))(data)

R.has,正如您所指出的,仅检查对象是否具有命名属性。 R.propIs检查属性是否属于给定类型。 R.propEq测试属性是否存在并等于给定值,更通用R.propSatisfies的检查属性值是否匹配任意谓词。

于 2016-03-18T12:03:59.820 回答
2

你可以试试这个功能:

function myFind(data, key, value) {
    return data.some(function(obj){
        return key in obj && obj[key] == value;
    });
}

参考:Array.some()

于 2016-03-16T21:46:32.860 回答