How to organize alphabetically a select obtained through a JSON?

Asked

Viewed 1,313 times

4

I rode a select through the JSON below, the only problem is that it follows the order of the key, how to arrange 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>

  • But your list is already in alphabetical order, anyway, if you have access do it in the backend.

  • Yes, the list is in alphabetical order but when mounting select it automatically sorts by key and not by value.

  • The alternatives presented are good, but this does not work. From the point of view of UX, you will have much more result for your experience, if you put a digitable field, which can suggest options based on the first characters inserted. In that case the order would be irrelevant, because he will need to insert at least A to see Acre Alagoas, Amapá. You’ll understand this better if you think of a broader way where you have a result with all cities of a state for example, and you can sort by ABC .. so that the person can find an option, and not objectively, for them to find

4 answers

7

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

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

After that 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 execute the sort simply call the function:

OrdenarPorNome();

4


unfortunately it is not possible to sort the keys of a JSON, but you can map your object to a array of objects, then you can use the function sort.

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 response.

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>
<select id="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();
  });
});

3

@Marcelo de Andrade is a little late, but he can do so too. This way, it will reorganize the keys and eventually if you write from the BD, it will record the Keys numbers for the respective states.

See 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.