简体   繁体   English

JavaScript遍历对象

[英]JavaScript Iterate over Object

I am using ReactJS with React-Bootstrap. 我正在将ReactJS与React-Bootstrap一起使用。 The service I am calling to get possible values for a combobox returns a JSON object. 我正在调用以获取组合框可能值的服务返回一个JSON对象。

{"1":"GLOBAL","2":"STORE","3":"COUNTRY","4":"REGION","5":"DISTRICT","6":"CUSTOM_LIST"}

I want to somehow turn iterate over this and create a SELECT with the options value being the integer, and the string value being what is displayed. 我想以某种方式对其进行迭代,并创建一个SELECT,其options值为整数,字符串值为所显示的内容。

<option value="1">GLOBAL</option>

How can a do that with it returning a JSON object, which appears to be a serialized Map. 如何用它返回一个JSON对象,该对象似乎是序列化的Map。

const data = { 
  "1":"GLOBAL",
  "2":"STORE",
  "3":"COUNTRY",
  "4":"REGION",
  "5":"DISTRICT",
  "6":"CUSTOM_LIST"
}

const optionEls = Object.keys(data).map(key => (
  <option value={key}>{data[key]}</option>
))

Or as a component receiving the data as props : 或作为接收data的组件作为props

const SelectComponent = ({data}) => (<select>
  {
    Object.keys(data).map(key => (
      <option value={key}>{data[key]}</option>
    ))
  }
</select>)

You should probably be able to do something like this in JSX: 您可能应该可以在JSX中执行以下操作:

<select>
  Array.from( myMap ).map(([key, value]) => ({ 
    <option value={key}>{value}</option>
  }));
</select>

where myMap is your JSON structure. 其中myMap是您的JSON结构。

Perhaps this can help you, I'm using a similar approach https://jsfiddle.net/69z2wepo/70835/ 也许这可以为您提供帮助,我正在使用类似的方法https://jsfiddle.net/69z2wepo/70835/

const data = {"1":"GLOBAL","2":"STORE","3":"COUNTRY","4":"REGION","5":"DISTRICT","6":"CUSTOM_LIST"};

function getDataToSelect(data){
   return _.map(_.keys(data),(key)=>{
        return {id:key, text:data[key]}
   })
}

const SelectElement = (props) => (
        <select>
         {
            [<option key={'none'}></option>].concat(props.options.map((opt, idx) => {
              return <option key={opt.id + '_' + idx} value={opt.id}>{opt.text}</option>
            }))
          }
        </select>
    );

ReactDOM.render(
  <SelectElement options={getDataToSelect(data)}  />,
  document.getElementById('container')
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM