Sometimes, we want to set a JavaScript array as options for a select element.
In this article, we’ll look at how to set a JavaScript array as options for a select element.
How to set a JavaScript array as options for a select element?
To set a JavaScript array as options for a select element, we can use the options.add method and the Option constructor.
For instance, we write:
<select>
</select>
to add the select drop down.
Then we write:
const options = [{
    "text": "Option 1",
    "value": "Value 1"
  },
  {
    "text": "Option 2",
    "value": "Value 2",
    "selected": true
  },
  {
    "text": "Option 3",
    "value": "Value 3"
  }
];
const selectBox = document.querySelector('select');
for (const o of options) {
  const {
    text,
    value,
    selected
  } = o
  selectBox.options.add(new Option(text, value, selected, selected));
}
to select the select element with querySelector.
Then we loop through the options array and call selectBox.options.add to add the options entry o into the select drop down by instantiating an Option instance.
The last argument is the default selected attribute value.
And the first 2 arguments are text and value for the option element.
Now we should see Option 2 is selected.
Conclusion
To set a JavaScript array as options for a select element, we can use the options.add method and the Option constructor.
