订单HTML根据数据顺序选择

订单HTML根据数据顺序选择,html,database,select,options,Html,Database,Select,Options,我有一个html选择,它使用数据库中的数据填充。查询是根据数据库中另一个字段的显示顺序进行排序的 返回的数据:id、名称 示例:{1:First,11:Second,10:Third} 添加到select时,排序基于id,如下所示: First Third Second 将数据添加到select时,如何保持数据的顺序?一个选项是将json对象转换为数组。每个属性都是数组中的一个元素,然后按名称对数组排序,并将其附加到select: var json = {"1":"First","11

我有一个html选择,它使用数据库中的数据填充。查询是根据数据库中另一个字段的显示顺序进行排序的

返回的数据:id、名称

示例:{1:First,11:Second,10:Third}

添加到select时,排序基于id,如下所示:

First  
Third  
Second

将数据添加到select时,如何保持数据的顺序?

一个选项是将json对象转换为数组。每个属性都是数组中的一个元素,然后按名称对数组排序,并将其附加到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>");
}

你可以

我通过更改返回数据的格式修复了此问题,使其包含显示顺序以及id和名称:


例如:[{id:4,name:name-One,display\u-order:1},{id:2,name:name-Two,display\u-order:2}]

谢谢阿尔瓦罗。您假设“值”是您正在排序的对象。我最初的问题是基于JSON数组中项目的顺序来选择顺序。您可能不希望这样做,因为JavaScript不能保证对象中的属性顺序。请参见此问题:。解决方案是返回具有不同结构的值,并在可能的情况下包括顺序。你必须从你拥有的{1:First,2:Second,}开始,在我看来很奇怪,但这可能只是我自己,进入一个更结构化的领域:[{id:1,value:First,order:1},{id:2,value:Second,order:3},]。一旦你有了这个结构,按照上面的解决方案,只需将比较函数从a.value和b.value更改为a.order和b.order