0

I have a html select that is populated using data from a database. The query is sorting based on a display order (another field in the DB).

Data Returned: id, name

Example: {"1":"First","11":"Second","10":"Third"}

When added to a select, the ordering is based on the id, as follows:

First  
Third  
Second

How can I maintain the ordering of the data when adding it to a select?

aynber
  • 22,380
  • 8
  • 50
  • 63

2 Answers2

0

One option would be to convert the json object into an array (each property would be an element in the array), then sort the array by name, and append it to the select:

var json = {"1":"First","11":"Second","10":"Third"};
var list = new Array(); 

// insert all the properties and their values into an array of objects
for(var propName in json) {
    list.push({ "id": propName, "value":json[propName] });
}

// sort the array using the value instead of the id
list.sort(function compare(a,b) {
              if (a.value < b.value)
                 return -1;
              else
                 return 1; // we consider that if they have the same name, the first one goes first
            });

// append the options in order in the select
for (var x = 0; x < list.length; x++) {
    $("#mySelect").append("<option value='" + list[x].id + "'>" + list[x].value + "</option>");
}

You can see it working on this jsfiddle.

Alvaro Montoro
  • 28,081
  • 7
  • 57
  • 86
  • Thanks Alvaro. You are assuming that the 'values' are what you are sorting on. My original question wants to base the select ordering on the order of the items in the JSON array. – Nathan Goss Jan 29 '15 at 06:06
  • What you want may not be possible because JavaScript does NOT guarantee property order in objects (see this question: http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order). – Alvaro Montoro Jan 29 '15 at 06:31
  • The solution would be to return the values with a different structure and including the order sequence (if possible). You would have to go from what you have `{"1":"First", "2":"Second", ...}` (that looks weird to me, but that may be just me) into something a bit more structured: `[ { "id":"1", "value":"First", "order":1}, {"id":"2","value":"Second","order":3}, ... ]`. Once you have that structure, follow the solution above, just changing the `compare` function from a.value and b.value to a.order and b.order – Alvaro Montoro Jan 29 '15 at 06:36
0

I fixed this issue by changing the format of the data that was returned, so that it contained the display order as well as the id and name:

eg: [{"id":"4","name":"Name One","display_order":"1"},{"id":"2","name":"Name Two","display_order":"2"}]