Ad

Ruby Rails .inject Equivalent In Node.js

- 1 answer

I'm very new in Node.js from Ruby Rails and although I'm using it for just a few weeks, I'm a bit confident about the basics.

However, I'm trying to convert a specific hash that uses inject in Ruby Rails. I'm not quite sure how to convert this in Javascript.

Can anyone help?

This is my Ruby Rails code:

result = CurrencyExchangeRates.all.inject({}) do |rates, c|
  rates[c.currency] = c.rate
  rates
end

# => {"one"=>"one", "two"=>"two", "three"=>"three"}

How can I do this correctly in Node.js

I'm looking at .forEach however I think this is just for arrays.

currency_exchange_rates.forEach(element => {

});
Ad

Answer

You can use reduce:

 const reducer = (rates, c) => Object.assign(rates, { [c.currency]: c.rate } )
 const result = all_rates.reduce(reducer, {})
Ad
source: stackoverflow.com
Ad