Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 480
Himmel Avatar asked Dec 18 '22 15:12

Himmel


2 Answers

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};
like image 193
Himmel Avatar answered Jan 06 '23 17:01

Himmel


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}
like image 42
Axel F Avatar answered Jan 06 '23 16:01

Axel F