简体   繁体   中英

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.

Looking at R.filter , it seems that _.filter only passes the object value and not the property. For instance, the example given in the 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?

After digging through the Ramda docs, I found R.omit which satisfies my particular use case.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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