为特定的val排序json对象?

时间:2016-07-19 07:43:23

标签: javascript json

这里是我的代码从db中根据年份选项获取现在我想按字母顺序显示。我已经尝试过sort()函数但是没有任何事情会发生请帮助。

$(document).ready(function () {

  //on change year change makes
  $('#years').change(function () {
    $('#makes').attr("disabled",true);
    $('#makes').empty();
    $('#makes').append($("<option></option>")
                       .attr("value", 0)
                       .text("Select Makes"));
    $.get('index.php?route=common/custom_search/get_makes_ajax&token=<?php echo $token; ?>',
          function (json) {
      if (json) {
        $.each(json, function (key, val) {
          $('#makes')
            .append($("<option></option>")
                    .attr("value", key)
                    .text(val));
          console.log(json);
        });
        $('#makes').removeAttr("disabled");
        //               console.log(json);
      } else {
        console.log('this is not working!');
      }

    });
    $('#models').attr("disabled",true);
    $('#sub_models').attr("disabled",true);
    $('#engines').attr("disabled",true);
    $('#parts').attr("disabled",true);
    $('#search_button').attr("disabled",true);
  });
}

1 个答案:

答案 0 :(得分:1)

我的猜测是你正在尝试对类似于这个的对象进行排序:

var json = {
      id1: 1998,
      id2: 1975,
      id3: 1983
    };

您不能在对象上使用sort()函数,因此您必须将数据重新编码为数组。更具体地说,它将成为一个对象数组。

var arr = [];

Object.keys(json).forEach(function(id) {
  arr.push({ id: id, year: json[id] });
});

我们现在可以对arr进行排序(此处按时间顺序排列):

arr.sort(function(a, b) { return a.year - b.year; });

最后,您需要稍微修改代码才能使用arr代替json

$.each(arr, function (key, val) {
  $('#makes')
    .append($("<option></option>")
            .attr("value", val.id)
            .text(val.year));
});