Sort & Populate HTML Select Element from Json
Sort and populate a html multi select element with the contents from JSON.
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/
HTML
<select id="select"></select>
JavaScript
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"
}
};
var sortedGroups = createSortedArray(json);
for(var index = 0; index < sortedGroups.length; index++) {
var group = sortedGroups[index];
var optGroup = document.createElement("optgroup");
optGroup.label = group.key;
var optionArray = createSortedArray(group.value);
for(var optionIndex = 0; optionIndex < optionArray.length; optionIndex++ ) {
var option = optionArray[optionIndex];
var opt = document.createElement("option");
opt.value = option.key;
opt.textContent = option.value;
optGroup.appendChild(opt);
}
document.getElementById("select").appendChild(optGroup);
}