Ramda,带或条件的过滤器

时间:2019-06-16 11:53:48

标签: ramda.js

let arr = [
  {
    name: 'Anna',
    q: {
      name: 'Jane'
    }
  }
];

const getName = R.prop('name');
const getQname = R.path(['q','name']);

这两个函数中的任何一个通过的过滤器。

类似的东西:

export const filterByName = (name) => 
R.filter(
  R.or(
   R.propEq(getName, name),
   R.propEq(getQname, name)
  )
)

不起作用。如何在R.filter中结合这两个功能?

3 个答案:

答案 0 :(得分:4)

将R.propEq与R.propEq一起用于name,并将R.pathEq与q.name一起使用:

const filterByName = (name) =>
  R.filter(
    R.either(
      R.propEq('name', name),
      R.pathEq(['q', 'name'], name)
    )
  )

const arr = [{"name":"Anna","q":{"name":"Jane"}},{"name":"Smite","q":{"name":"Jane"}},{"name":"Another","q":{"name":"One"}}];

console.log(filterByName('Anna')(arr))
console.log(filterByName('Jane')(arr))
console.log(filterByName('XXX')(arr))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

如果要使用外部函数提取值,则可以使用R.pipe。使用R.juxt提取所有属性值,然后使用带有R.equal的R.any检查是否相等。

const getName = R.prop('name');
const getQname = R.path(['q','name']);

const filterByName = (name) =>
  R.filter(
    R.pipe(
      R.juxt([getName, getQname]), // get all names
      R.any(R.equals(name)) // check if any of the equals to name
    )
  )

const arr = [{"name":"Anna","q":{"name":"Jane"}},{"name":"Smite","q":{"name":"Jane"}},{"name":"Another","q":{"name":"One"}}];

console.log(filterByName('Anna')(arr))
console.log(filterByName('Jane')(arr))
console.log(filterByName('XXX')(arr))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

答案 1 :(得分:1)

我将使用either,因为它可以与以下功能配合使用:

export const filterByName = (name) => 
  R.filter(R.either(
   R.propEq('name', name),
   R.pathEq(['q', 'name'], name)));

const nameIs = R.propEq('name');
const qNameIs = R.pathEq(['q','name']);

export const filterByName = (name) => 
  R.filter(R.either(nameIs(name), qNameIs(name)));

答案 2 :(得分:0)

您还可以使用无点样式编写此代码:

const nameIs = R.converge(R.or, [
  R.pathEq(['name']),
  R.pathEq(['q', 'name']),
]);

const onlyAnna = R.filter(nameIs('Anna'));
const onlyGiuseppe = R.filter(nameIs('Giuseppe'));

const data = [
  { name: 'Anna', q: { name: 'Jane' } },
  { name: 'Mark', q: { name: 'Mark' } },
  { name: 'Giuseppe', q: { name: 'Hitmands' } },
];

console.log('Anna', onlyAnna(data));
console.log('Giuseppe', onlyGiuseppe(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>