按名称订购$ each

I am trying to figure why my ajax $each alters the way my list of names gets printed?

I have an json string like this:

[{"name":"Adam","len":1,"cid":2},{"name":"Bo","len":1,"cid":1},{"name":"Bob","len":1,"cid":3},{"name":"Chris","len":1,"cid":7},{"name":"James","len":1,"cid":5},{"name":"Michael","len":1,"cid":6},{"name":"Nick","len":1,"cid":4},{"name":"OJ","len":1,"cid":8}]

Here all the names are sorted in alphabetic order, but when getting them out they are sorted by "cid"? Why, and how can I change this?

Here is my jQuery:

var names = {};
$.getJSON('http://mypage.com/json/names.php', function(data){ 

    $.each(data.courses, function (k, vali) {
        names[vali.cid] = vali.name;
    });
});

I guess its because "names[vali.cid]", but I need that part to stay that way. Can it still be done?

Hoping for help and thanks in advance :-.)

Ordering inside an object is not really defined or predictable when you iterate over it. I would suggest sorting the array based on an internal property:

var names = [];
$.getJSON('http://mypage.com/json/names.php', function(data){ 
    $.each(data.courses, function (k, vali) {
        names.push({name: vali.name, cid: vali.cid});
    });

    names.sort(function(a, b) {
        return a.name.localeCompare(b.name);
    });
});

Now you have an array that is ordered and you can iterate over it in a predictable order as well.

  1. There is no "ajax $each" - you probably mean the jQuery function.
  2. With "when getting them out" I presume you mean something like console.debug(names) after your $each call
  3. Objects aren't ordered in javascript per definition, so there is no more order in your variable "names". Still, most javascript implementations today (and all the ones probably important to you - the ones used in the most used browsers) employ a stable order in objects which normally depends on the order you insert stuff.

All this said, there can probably be 3 reasons you're not getting what you're expecting:

  1. Try console.debug(data) and see what you get - the order as you want it?
  2. As you don't explicitly state how you debug your stuff, the problem could be in the way you output and not the data is stored. Here too try console.debug(names).
  3. You're using a function which dereferences on expection, like console.*. This means if you console.debug() an object, the displayed values will depend on the moment you unfold the displayed tree in your browser, not when the line was called!