What is the best way to add options to a select from a JavaScript object with jQuery?


What is the best method for adding options to a <select> from a JavaScript object using jQuery?

I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there.

This is what I did:

selectValues = { "1": "test 1", "2": "test 2" };

for (key in selectValues) {
  if (typeof (selectValues[key] == 'string') {
    $('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');

A clean/simple solution:

This is a cleaned up and simplified version of matdumsa's:

$.each(selectValues, function(key, value) {
          .append($('<option>', { value : key })

Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().

9/5/2020 1:22:01 PM

Accepted Answer

The same as other answers, in a jQuery fashion:

$.each(selectValues, function(key, value) {   
                    .attr("value", key)
6/1/2020 2:55:08 PM

var output = [];

$.each(selectValues, function(key, value)
  output.push('<option value="'+ key +'">'+ value +'</option>');


In this way you "touch the DOM" only one time.

I'm not sure if the latest line can be converted into $('#mySelect').html(output.join('')) because I don't know jQuery internals (maybe it does some parsing in the html() method)


This is slightly faster and cleaner.

var selectValues = {
  "1": "test 1",
  "2": "test 2"
var $mySelect = $('#mySelect');
$.each(selectValues, function(key, value) {
  var $option = $("<option/>", {
    value: key,
    text: value
<script src=""></script>
<select id="mySelect"></select>



var list = $("#selectList");
$.each(items, function(index, item) {
  list.append(new Option(item.text, item.value));

Vanilla JavaScript

var list = document.getElementById("selectList");
for(var i in items) {
  list.add(new Option(items[i].text, items[i].value));

If you don't have to support old IE versions, using the Option constructor is clearly the way to go, a readable and efficient solution:

$(new Option('myText', 'val')).appendTo('#mySelect');

It's equivalent in functionality to, but cleaner than:

$("<option></option>").attr("value", "val").text("myText")).appendTo('#mySelect');

This looks nicer, provides readability, but is slower than other methods.

$.each(selectData, function(i, option)

If you want speed, the fastest (tested!) way is this, using array, not string concatenation, and using only one append call.

auxArr = [];
$.each(selectData, function(i, option)
    auxArr[i] = "<option value='" + + "'>" + option.title + "</option>";