ReynierPM ReynierPM - 1 year ago 56
Javascript Question

How to build optgroup with option from JSON?

I have the following JSON input:

[
{
"No Value in Support": [
{
"5": "In house support (HIS)"
},
{
"6": "No interaction with support (NIS)"
},
{
"7": "No value in SWR maintenance (NVS)"
},
{
"8": "Support from other 3rd party (SOT)"
}
]
}
]


and I am trying to build something like this:

<select id="sel" name="id">
<optgroup label="Alaskan/Hawaiian Time Zone">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</optgroup>
</select>


where the
label
of the
optgroup
is the
key
on the main array, the
value
of each
option
is the
key
on the subarray and the text is the value.

For example this is an expected output from the sample above:

<select id="sel" name="id">
<optgroup label="No Value in Support">
<option value="5">In house support (HIS)</option>
<option value="6">No interaction with support (NIS)</option>
<option value="7">No value in SWR maintenance (NVS)</option>
<option value="8">Support from other 3rd party (SOT)</option>
</optgroup>
</select>


This is what I've done so far:

var sel_content = '';

$.each(data, function(idx, arr) {
sel_content += '<optgroup label="' + idx + '">';
$.each(arr, function(arr_idx, arr_value) {
sel_content += '<option value="' + arr_idx + '">' + arr_value + '</option>';
});
sel_content += '</optgroup>';
});

$('#sel').append(sel_content);


But if you look here you'll see isn't working properly because I am getting Object as the values. Can any give me some help?

Answer Source

Since your JSON is such that it's a single item array of objects you have to change your code to be the first item of the array:

  var sel_content = '';

  $.each(data[0], function(idx, arr) {
    sel_content += '<optgroup label="' + idx + '">';
    $.each(arr[0], function(arr_idx, arr_value) {
      sel_content += '<option value="' + arr_idx + '">' + arr_value + '</option>';
    });
    sel_content += '</optgroup>';
  });

  $('#sel').append(sel_content);

Here is a fiddle of it working now: https://jsfiddle.net/y086oomp/4/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download