0

I am sending from cities.php a json string like this:

[{"name":"Boston","len":1,"cid":"292"},{"name":"Miami","len":1,"cid":"243"},{"name":"Washington","len":1,"cid":"36"},{"name":"Alabama","len":1,"cid":"5"},{"name":"New York","len":1,"cid":"435"}]

I then retrieve it at my cities.html like this:

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

I am taking the json and putting into a javascript object and it works just perfect and comes out like this:

{ 
5: 'Alabama', 
36: 'Washington', 
243: 'Miamai', 
292: 'Boston',
435: 'New York'
};

This is almost OK but... It is not in alphabetical order?

I need to sort this by name before getting into the cities{} object...

How do I accomplish this?

Hoping for help and thanks in advance...

Mansa
  • 2,277
  • 10
  • 37
  • 67

1 Answers1

1

write a compare function

function compare(a,b) {
  if (a.name < b.name)
     return -1;
  if (a.name > b.name)
    return 1;
  return 0;
}

then sort your data

var cities = {};
$.getJSON('http://mypage.com/json/cities.php', function(data){ 
    data.sort(compare);
    $.each(data, function (k, vali) {
        cities[vali.cid] = vali.name;
    });
});
svillamayor
  • 546
  • 3
  • 7
  • I tried this solution, but with no luck... It seems like the $.each part sorts it afterwards... Any ideas? – Mansa Jul 24 '13 at 21:10
  • the array should be sorted correctly, maybe the problem is how are you using the cities object – svillamayor Jul 24 '13 at 21:22