首页 文章

Ramdajs:如何基于对象的嵌套属性进行过滤

提问于
浏览 126
0
const abby = {name: 'Abby', attributes: {age: 7, hair: 'blond'}};
const fred = {name: 'Fred', attributes: {age: 12, hair: 'brown'}};
const rusty = {name: 'Rusty', attributes: {age: 10, hair: 'brown'}};
const alois = {name: 'Alois', attributes: {age: 15, disposition: 'surly'}};
const kids = [abby, fred, rusty, alois];

// current code
console.log(R.filter(R.compose(R.propEq('hair', 'blond'), R.props('attributes')))(kids));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>

我想得到年龄> 10的物品 . 我尝试使用compose但不幸的是它不起作用 . 我仍然是ramda的新人 .

1 回答

  • 2

    由于您正在测试嵌套属性,因此可以使用pathSatisfies

    如果给定路径的指定对象属性满足给定谓词,则返回true;否则返回true . 否则是假的 .

    const {filter, lt, pathSatisfies} = R;
    
    const abby = {name: 'Abby', attributes: {age: 7, hair: 'blond'}};
    const fred = {name: 'Fred', attributes: {age: 12, hair: 'brown'}};
    const rusty = {name: 'Rusty', attributes: {age: 10, hair: 'brown'}};
    const alois = {name: 'Alois', attributes: {age: 15, disposition: 'surly'}};
    const kids = [abby, fred, rusty, alois];
    
    console.log(
    
      filter(pathSatisfies(lt(10), ['attributes', 'age']), kids)
    
    )
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
    

相关问题