Leon Gaban
Leon Gaban

Reputation: 39018

How to use Ramda to find matching object in Array by key value

Ramda REPL example

var portfolio = [{ticker: "aa"},  {ticker: "bb"}];

var ticker = {ticker:"aa"};

var exist = R.find(R.propEq('ticker', ticker), portfolio)

console.log(exist)

Currently this is giving me undefined, however R.propEq should find the matching object by key ticker in port I thought?

Upvotes: 8

Views: 19775

Answers (2)

Scott Sauyet
Scott Sauyet

Reputation: 50797

As you say, you can solve it by passing in the key to propEq:

R.find(R.propEq('ticker', 'aa'), port)

Another option is to use the eqProps function, which tests if two objects match for the named key:

R.find(R.eqProps('ticker', ticker), port)

You can see the first or second version in the Ramda REPL.

Upvotes: 18

Leon Gaban
Leon Gaban

Reputation: 39018

Ah it was a simple mistake, I forgot to pass in the exact key from the ticker object.

R.propEq('ticker', ticker.ticker)

This is how I now solve my problem in my app:

const exists = R.find(R.propEq('ticker', this.ticker.ticker));
this.inPortfolio = !!exists(portTickers);
console.log('this.inPortfolio', this.inPortfolio)
// True or false

Upvotes: 0

Related Questions