Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter out specific keys from object using Ramda?

http://ramdajs.com/0.21.0/docs/#prop

Ramda Repl

var myObject = {a: 1, b: 2, c: 3, d: 4};

var newObject = R.filter(R.props('a'), myObject);
//var newObject = R.filter(R.equals(R.props('a')), myObject);

console.log('newObject', newObject);

Right now the code above is returning the entire object:

newObject {"a":1,"b":2,"c":3,"d":4}

What I would like to do is just return a new object with just the 'a' key. Or a new object with the a and b keys.

like image 521
Leon Gaban Avatar asked Apr 10 '17 20:04

Leon Gaban


2 Answers

pickBy()

const getOnlyGoods = R.pickBy((_, key) => key.includes('good'));

const onlyGoods = getOnlyGoods({
  "very good":    90,
  "good":         80,
  "good enough":  60,
  "average":      50,
  "bad":          30,
  "😡":           10,
});

console.log(onlyGoods);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
like image 183
Yairopro Avatar answered Oct 15 '22 09:10

Yairopro


Use pick:

let newObj = R.pick(['a'], oldObj);

If your filtering criteria is more complex than just existence, you can use pickBy to select via arbitrary predicate functions.

like image 37
Jared Smith Avatar answered Oct 15 '22 09:10

Jared Smith