How to alphabetize a select obtained through a JSON?

4

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><selectid="estado" name="estado" class="form-control input">
  <option value="">Selecione o Estado</option>
</select>
    
asked by anonymous 11.07.2016 / 19:54

4 answers

4
Unfortunately, it is not possible to sort the keys of a JSON , however you can map your object to a array of objects, so you can use the sort function.

var data = {
    "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"
};

var _estado = document.getElementById("estado");
var estados = Object.keys(data).map(function(key) {
  return { codigo: key, nome: data[key] };
});
estados.sort(function (estadoA, estadoB) {
  return estadoA.nome > estadoB.nome ? 1 : -1;
});
estados.forEach(function(estado) {
  var option = document.createElement("option");
  option.value = estado.codigo;
  option.textContent = estado.nome;
  _estado.appendChild(option);
})
<select id="estado" name="estado" class="form-control input">
</select>

EDIT

Thanks to @MagicHat, I saw that I could use Object.keys to simplify my answer.

    
11.07.2016 / 20:30
7

First of all, I would like to suggest an edition of your Json so that the return is readable, someone can tinker with the code that one day is not you! Then I would do something about it:

var UFs =    
[ 
    {Id: 12, UF: "Acre"},
    {Id: 27, UF: "Alagoas"},
    {Id: 16, UF: "Amapá"},
    {Id: 13, UF: "Amazonas"},
    .
    .
    .
];

After this I would do a very simple sort 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 order by Id too!

To execute the order, just call the function:

OrdenarPorNome();
    
12.07.2016 / 02:34
4

@Marcelo an alternative is to sort with a js function. It would look something like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="estado" name="estado" class="form-control input">
  <option value="">Selecione o Estado</option>
</select>

        $(document).ready(function() {
            function orderSelect(){
                var options = $('select.whatever option');
                var arr = options.map(function(_, o) {
                    return {
                        t: $(o).text(),
                        v: o.value
                    };
                }).get();
                arr.sort(function(o1, o2) {
                    return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0;
                });
                options.each(function(i, o) {
                    console.log(i);
                    o.value = arr[i].v;
                    $(o).text(arr[i].t);
                });
            }

  $.getJSON("/estados.json", function(estados) {
    $.each(estados, function(codigo, nome) {
      $('select#estado').append($('<option>').text(nome).attr('value', codigo));
    });
    orderSelect();
  });
});
    
11.07.2016 / 20:31
3

@Marcelo de Andrade is a little late, but he can do that too. In this way, it will rearrange the keys and eventually if it is to write from the DB, it will record the keys numbers relative to the respective states.

See it working: FIDDLE

<body>
<select id="estado" name="estado" class="form-control input">

</select>
<script>
html="";    
var data = 
{
"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"
 };

 var arr = Object.keys(data).map(function(k) { return data[k] });
 arr.sort();
 for(var key in arr) {
 html += "<option value=" + key + ">" +arr[key] + "</option>";}

 document.getElementById("estado").innerHTML = html;

 </script>
 </body>
    
11.07.2016 / 22:47