Reputation: 6909
I have seen a similar question here (how to display json data in dropdown using reactj), but it does not answer my query.
I have some JSON data coming in from an ajax request in my react app:
"quotes":{
"USDAED":3.6732,
"USDAFN":77.588904,
"USDALL":103.298421,
"USDAMD":528.084946,
"USDANG":1.795181,
"USDAOA":628.150147,
"USDARS":92.5812
}
Its a list of currencies and their conversion rates.
I need to render a select dropdown list out of it in a react component such that the json data is transformed into keys and values:
<select className="dropdown">
<option key="USDAED" value="3.6732">USDAED</option>
<option key="USDAFN" value="77.588904">USDAFN</option>
...
Is there an easy way to traverse the json data and create a select dropdown in JSX?
Upvotes: 0
Views: 3101
Reputation: 655
you can iterate through your object keys
Updated my answer to show html
var data = {
"quotes": {
"USDAED": 3.6732,
"USDAFN": 77.588904,
"USDALL": 103.298421,
"USDAMD": 528.084946,
"USDANG": 1.795181,
"USDAOA": 628.150147,
"USDARS": 92.5812
}
};
var result=[];
for (let key in data.quotes) {
var ele = document.getElementById('sel');
result.push({key:key,value:data.quotes[key]})
ele.innerHTML += '<option value="' + key + '">' + data.quotes[key] + '</option>';
}
console.log(result)
<select className="dropdown" id="sel">
<option value="">-- Select --</option>
</select>
Upvotes: 0
Reputation: 1101
I see only one difference between your situation and the SO example: in the example the list of items is an array, in your situation it's the fields of an object.
using Object.keys() you can get an array of fields, and use a map on this array to display all the options
<select>
{Object.keys(quotes).map(element => <option key={element} value={quotes[element]}>{element}</option>)}
</select>
https://codepen.io/sanjar/pen/YzNLRWE?editors=0011
Upvotes: 1