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/
//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 =...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.