jkratz55
jkratz55

Reputation: 881

JavaScript Iterate over Object

I am using ReactJS with React-Bootstrap. The service I am calling to get possible values for a combobox returns a JSON object.

{"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.

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

How can a do that with it returning a JSON object, which appears to be a serialized Map.

Upvotes: 0

Views: 103

Answers (3)

Gino Llerena
Gino Llerena

Reputation: 516

Perhaps this can help you, I'm using a similar approach 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')
);

Upvotes: 0

Bal&#225;zs &#201;des
Bal&#225;zs &#201;des

Reputation: 13807

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:

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

Upvotes: 1

Gregg
Gregg

Reputation: 35864

You should probably be able to do something like this in JSX:

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

where myMap is your JSON structure.

Upvotes: 0

Related Questions