0

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?

1
  • Object.entries() is your friend. Commented Apr 14, 2021 at 21:33

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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>

2 Comments

I see. So this converts the data into an array of objects. How then do I convert this array to a select/option list in my render function?
Thank you. I’ve upvoted your answer, but someone else has provided a much cleaner solution, which I’ve accepted.

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.