kchol87
kchol87

Reputation: 21

How to create a list of <option> entries from .json file with vanilla JS?

I need to create list of HTML form entries from a .json file containing a key and a value. No problem with fetching the file and so on. Been fighting with loops all day, but nothing seems to work. This is part of my .json file:

{
"City": "0",
"Another City": "1",
"Yet Another City": "2",
(...)
}

And this is what I would like to achieve in HTML (add options through innerHTML e.g.):

<option id="0">City</option>
<option id="1">Another City</option>
<option id="2">Yet Another City</option>
(...)

I was trying loops and using Object.keys(ObjectVariableName)[0] but can't get it to work. I would appreciate your help.

Upvotes: 1

Views: 353

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22265

use add() and new option() methods

const  mySelect = document.getElementById('my-select')
  ,    data = 
        { 'City': '0'
        , 'Another City': '1'
        , 'Yet Another City': '2'
        }
  ;
for (const [key, value] of Object.entries(data))
  {
  mySelect.add(new Option(key, value))     
  }

console.log(mySelect.innerHTML);
<select name="xxx" id="my-select"></select>

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28404

You need to create option elements, set the text and value of each, and then append them to the select:

let obj = {
"City": "0",
"Another City": "1",
"Yet Another City": "2",
}
let select = document.getElementById("myList");
for (var key in obj) {
     var option = document.createElement("option");
     option.text = key;
     option.value = obj[key];
     select.add(option);
}
console.log(select.innerHTML);
<select id="myList"></select>

Upvotes: 1

Related Questions