Sort & Populate HTML Select Element from Json

Sort and populate a html multi select element with the contents from JSON. I modified it to not attach empty optgroups. BY StackOverflow user: http://stackoverflow.com/users/361762/dave-%CD%A4%CD%AE%CD%A3%CD%A9 In Response to question: http://stackoverflow.com/questions/25431819/

by Donavon Lerman

HTML

<select id="select" multiple="multiple" style="height:300px;width:100px;"></select>
&nbsp;
<select id="select1" multiple="multiple" style="height:300px;width:100px;"></select>

JavaScript

//take an object and loop through all the properties
            //each property goes into an array and is sorted
            //loop through the sorted array and build an output array of objects
            //objects in output have 2 properties
            //key = original property name, value = original property value
            function createSortedArray(obj) {
                var returnArray = [];
                var sortingArray = [];
                for(var property in obj) {
                    sortingArray.push(property);
                }
                sortingArray.sort();
                for(var index = 0; index < sortingArray.length; index++) {
                    var property = sortingArray[index];
                    var newObject = {};
                    newObject.key = property;
                    newObject.value = obj[property];
                    returnArray.push(newObject);
                }
                return returnArray;
            }


var json = {
				"group 3": {
				  "value33": "label33",
				  "value13": "label13",
				  "value23": "label23"
				},
				"group 1": {
				  "value21": "label21",
				  "value31": "label31",
				  "value11": "label11"
				},
				"group2": {
				  "value22": "label22",
				  "value12": "label12",
				  "value32": "label32"
				}
			  };

//sort source object with function above and loop through results
var sortedGroups = createSortedArray(json);
for(var index = 0; index < sortedGroups.length; index++) {
    var group = sortedGroups[index];
    
    //create optgroup tag and assign label property
    if(group.key) {
        var optGroup = document.createElement("optgroup");
        optGroup.label = group.key;
    }
    
    //sort the properties of the current group using our function again
    var optionArray = createSortedArray(group.value);
    for(var optionIndex = 0; optionIndex <  optionArray.length; optionIndex++ ) {
        //options are now sorted, just add to the optgroup
        var option =...