0

I have a currency map file like this:

currency.js which has currencies in an object which looks like this:

module.exports = {
  'United States': 'USD',
  'India': 'Rupee',
  'Mexico': 'Peso',
}

And my code looked like this:

'use strict';


const React = require('react');
const currency = require('js/legacy/core/models/countries');

const RegistrationCountryField = ({onCurrencyNameSet, currencyName}) => {
    const currencyNames = ['Select Currency'].concat(Object.values(currency));
    const currencyOptions = function(currencyName) {
        return <option value={currencyName}>{currencyName}</option>;
    };
    return (
        <fieldset className="form-group">
            <label className="group-label">Country</label>
            <select onChange={onCurrenctNameSet} className="form-group-control" value={currency}>
                {countryNames.map(currencyOptions)}
            </select>
        </fieldset>
    );
};

However, Object.values was not supported and I had to use Object.keys. So code looked like this:

const currencyOptions = Object.keys(currency).map((currenyCode) =>
    <option key={currencies[currenyCode]}>{countries[currenyCode]}</option>
);

My question is 'How do i append select currency' in the last code snippet?

1 Answer 1

1

since array.map returns a new array, and since array methods can be chained, you can just do this:

const currencyOptions = Object.keys(currency).map((currenyCode) =>
  <option key={currencies[currenyCode]}>{countries[currenyCode]}</option>
)
.concat(
  <option key="selectOption">Select currency</option>
);

or if you want the select-currency option to be first, you can reverse it:

const currencyOptions = 
  [<option key="selectOption">Select currency</option>] // array of length 1
  .concat(Object.keys(currency).map((currenyCode) =>
    <option key={currencies[currenyCode]}>{countries[currenyCode]}</option>
  );

or use the spread operator:

const currencyOptions = [
  <option key="selectOption">Select currency</option>,
  ...Object.keys(currency).map((currenyCode) =>
<option key={currencies[currenyCode]}>{countries[currenyCode]}</option>
];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.