Question:
I set up a select
through JSON
below, the only problem is that it follows the order of the key, how to organize it alphabetically?
{
"12": "Acre",
"27": "Alagoas",
"16": "Amapá",
"13": "Amazonas",
"29": "Bahia",
"23": "Ceará",
"53": "Distrito Federal",
"32": "Espírito Santo",
"52": "Goiás",
"21": "Maranhão",
"51": "Mato Grosso",
"50": "Mato Grosso do Sul",
"31": "Minas Gerais",
"15": "Pará",
"25": "Paraíba",
"41": "Paraná",
"26": "Pernambuco",
"22": "Piauí",
"33": "Rio de Janeiro",
"24": "Rio Grande do Norte",
"43": "Rio Grande do Sul",
"11": "Rondônia",
"14": "Roraima",
"42": "Santa Catarina",
"35": "São Paulo",
"28": "Sergipe",
"17": "Tocantins"
}
$(document).ready(function() {
$.getJSON("/estados.json", function(estados) {
$.each(estados, function(codigo, nome) {
$('select#estado').append($('<option>').text(nome).attr('value', codigo));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="estado" name="estado" class="form-control input">
<option value="">Selecione o Estado</option>
</select>
Answer:
First I would like to suggest an edit of your Json so that the return is readable, someone can mess with the code that one day it won't be you! So I would do something along the lines:
var UFs =
[
{Id: 12, UF: "Acre"},
{Id: 27, UF: "Alagoas"},
{Id: 16, UF: "Amapá"},
{Id: 13, UF: "Amazonas"},
.
.
.
];
After that I would make a very simple sorting function:
function OrdenarPorNome()
{
UFs.sort(function (a, b) { return a.UF > b.UF ? 1 : -1; });
} // Como o amigo acima já observou!
function OrdenarPorID()
{
UFs.sort(function (a, b) { return a.Id > b.Id ? 1 : -1; });
}
Even if you want to sort by Id too!
To perform the ordering, just call the function:
OrdenarPorNome();