简体   繁体   English

按Ramda.js中的属性过滤对象

[英]Filtering an object by property in Ramda.js

I'm new to using Ramda.js and am wondering how I can filter an object based on specified properties. 我是使用Ramda.js的新手,我想知道如何根据指定的属性过滤对象。

Looking at R.filter , it seems that _.filter only passes the object value and not the property. 查看R.filter ,似乎_.filter仅传递对象 ,而不传递属性。 For instance, the example given in the REPL: 例如,REPL中给出的示例:

var isEven = (n, prop) => {
  console.log(typeof prop);

  // => 
  // undefined
  // undefined
  // undefined
  // undefined

  return n % 2 === 0;
}

R.filter(isEven, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4}

If I have the following object: 如果我有以下对象:

const obj = {a: 1, b: 2, c: 3};

My desired result would be: 我想要的结果是:

const filterProp = (x) => /* some filter fn */;

filterProp('b')(obj);

// => {a: 1, c: 3};

How can I use Ramda to filter the properties of an object? 如何使用Ramda过滤对象的属性?

After digging through the Ramda docs, I found R.omit which satisfies my particular use case. 在浏览Ramda文档之后,我发现R.omit可以满足我的特定用例。

const obj = {a: 1, b: 2, c: 3};

R.omit(['b'], obj);

// => {a: 1, c: 3};

Use the pickBy method which allows you to filter a collection based on the keys. 使用pickBy方法可让您根据键过滤集合。

const obj = {a: 1, b: 2, c: 3};
var predicate = (val, key) => key !== 'b';
R.pickBy(predicate, obj);
// => {a: 1, c: 3}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM