如何在React js中将地图转换为数组时连接?

时间:2016-12-19 15:24:31

标签: javascript reactjs

我有这样的货币地图文件:

context.Feeds.Update(f=>new Feed{CategoryId=1}); 在对象中有货币,如下所示:

currency.js

我的代码看起来像这样:

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

但是,不支持Object.values,我不得不使用Object.keys。所以代码看起来像这样:

'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>
    );
};

我的问题是“如何在最后一个代码段中附加选择货币?”

1 个答案:

答案 0 :(得分:1)

因为array.map返回一个新数组,并且由于数组方法可以链接,所以你可以这样做:

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

或者如果您希望将select-currency选项放在第一位,您可以将其反转:

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>
  );

或使用spread operator

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