开发者

jQuery $.get() Order Doesn't Match

开发者 https://www.devze.com 2023-02-13 16:10 出处:网络
The php returns my arrays ordered by name, but when I use $.(get), they\'re ordered by id. { \"34\":{\"id\":\"34\",\"name\":\"Amber\",\"assigned\":1},

The php returns my arrays ordered by name, but when I use $.(get), they're ordered by id.

{
"34":{"id":"34","name":"Amber","assigned":1},
"72":{"id":"72","name":"Bob","assigned":0},
"7":{"id":"7","name":"Charlie","assigned":0},
"3":{"id":"3","name":"Gary","assigned":1}
}

$.get("/assign", { clasa: clasaDL.attr('id') },
  fu开发者_C百科nction(data){
    var checked, boxes = "";
    $.each(data, function(n, val) {
      checked = (val.assigned == 1) ? 'checked="yes"' : '';
      boxes += '<input type="checkbox" ' + checked + ' value="' + val.id + '" />' + val.name;
    });

  $('#dialog').html('<form id="assign">' + boxes + '</form>');
}, "json");

Question is: How can I order it by name, and not by id?


JavaScript objects are not ordered. While most browser keep the initial order, e.g. Chrome doesn't.

If you want sorted data, use an array - if you need access using a key which is not suitable for an array (non-numeric or lots of unused keys between the actual element keys), create an object containing key => array index mappings.

So your JSON could look like this:

{
    "data": [
        {"id":"34","name":"Amber","assigned":1},
        {"id":"72","name":"Bob","assigned":0},
        {"id":"7","name":"Charlie","assigned":0},
        {"id":"3","name":"Gary","assigned":1}
    ],
    "mappings": {"34": 0, "72": 1, "7": 2, "3": 3}
}

Then you could iterate over data or access an element by its id using data[mappings['yourid']]

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号