jquery使用匹配相同顺序的json填充选择选项

时间:2017-03-14 12:16:56

标签: javascript jquery json

我有以下json数据:

 {
      "324": "Aguacate",
      "196": "Fresa",
      "7875": "Mandarina",
      "197": "Platano",
      "9517": "Uvas"
 }

出于任何原因,当我填充目标选择下拉列表选项时,它会以不同的顺序(按ID)返回选项:

 {
      "196": "Fresa",
      "197": "Platano",
      "324": "Aguacate",
      "7875": "Mandarina",
      "9517": "Uvas"
 }

考虑到脚本如下:

  $.getJSON("http://path/to/blabla.json", customfunction);

  function customfunction(data) {

        var $select = $('#mymail_data_socio'); 

        // First, empty the select field
        $select.find('option').remove();

        $.each(data,function(key, value) {
              $select.append('<option value=' + key + '>' + value + '</option>');
        });

  }

有没有办法以与我的json文件相同的顺序返回选项?我应该如何重写我的脚本才能实现它?

谢谢!

2 个答案:

答案 0 :(得分:2)

这是一个特定于浏览器的问题(基本上是chrome问题),其中浏览器javascript引擎按顺序遍历对象属性(数字属性):https://bugs.chromium.org/p/v8/issues/detail?id=164

您可以使用前缀,然后在循环中将其替换为:

var obj = {
      "id_324": "Aguacate",
      "id_196": "Fresa",
      "id_7875": "Mandarina",
      "id_197": "Platano",
      "id_9517": "Uvas"
 };
 
 function customfunction(data) {

        var $select = $('#mymail_data_socio'); 

        // First, empty the select field
        $select.find('option').remove();

        $.each(data,function(key, value) {
              $select.append('<option value=' + key.replace('id_', '') + '>' + value + '</option>');
        });

  }
  
  customfunction(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mymail_data_socio"></select>

答案 1 :(得分:1)

另一种选择是使用JSONArray并且可以使用内部循环进行迭代(可以通过多次迭代非常繁忙),这将以指定的相同顺序给出所需的结果。

here is the example with both ways