I need to sort JSON object alphabetically.
I want to send it to array of objects and then sort. Now I was successful in sending it to multidimensional array and sort but still not able to sort array of objects.
I have object.
var Response = {
"10001": "Fort Worth",
"10002": "Dallas",
"32402": "Austin"
};
I send it to array.
var sort_array_of_array = [];
for (var my_key in Response) {
var inner_array = [];
inner_array[0] = my_key;
inner_array[1] = Response[my_key];
sort_array_of_array.push(inner_array);
}
In result I get an array
sort_array_of_array: Array[3]
0: Array[2]
0: "10001"
1: "Fort Worth"
length: 2
1: Array[2]
0: "10002"
1: "Dallas"
length: 2
2: Array[2]
length: 3
I sorted it.
sort_array_of_array.sort(function(a, b)
{
// if they are equal, return 0 (no sorting)
if (a[1] == b[1]) { return 0; }
if (a[1] > b[1])
{
// if a should come after b, return 1
return 1;
}
else
{
// if b should come after a, return -1
return -1;
}
});
I checked the sorted array.
<div id="my_after_sort"></div>
for (i = 0; i < sort_array_of_array.length; ++i) {
//alert(sort_array_of_array[i][0]);
$('#my_after_sort').append(sort_array_of_array[i][1]);
}
But if I send the original object to array of objects I fail to sort it.
var sort_array_of_object = [];
for (var key in Response) {
sort_array_of_object.push({key:Response[key]});
}
Is it possible to sort this array of objects and how to do it?