Keep order of items in JSON

3

Can you keep the order of items that came in JSON of a API ?

This is how it comes from API :

  

{"6":"Abadia","218":"Abel Reis","44":"Alexandre Campos - Jardim","13":"Alfredo Freire I","174":"Alfredo Freire II","186":"Alfredo Freire III","217":"Alfredo Freire IV","189":"Alvorada I, Jardim","190":"Alvorada II, Jardim","55":"Am\u00e9rica - Jardim","80":"Amoroso Costa","254":"Anita, Jardim","137":"Antonia"}

And when I use it in select for example JSON is being organized by index and not texto , ie,

  

1: "Center"
  2: "Saint Benedict"
  3: "Santa Maria"
  6: "Abbey"
  8: "Great Horizon"
  9: "Good View"
  10: "Mercês"
  11: "Rec. Dos Bandeirantes"

    
asked by anonymous 23.03.2018 / 19:37

2 answers

3
  

When key names are just numeric, JavaScript   automatically reorders in numerical order.

But you can reorder select options using sort() . After popular select , use the code below, which will restructure the options by sorting them alphabetically by text:

// seleciona o select. Altere para o id ou classe usada no select
var sel = document.body.querySelector("select");

// seleciona as options como array
var sel_opts = Array.apply(null, sel.childNodes);

// aplico o sort
sel_opts.sort(function(a,b) {
    return a.text.localeCompare(b.text);
});

// vou criar a coleção das options em HTML
opts = "";
for(var chave of sel_opts) {
   opts += chave.outerHTML;
}

// substituo as options ordenadas no select
sel.innerHTML = opts;

Example:

var obj = {
   "6":"Abadia",
   "218":"Abel Reis",
   "1":"Centro",
   "2":"São Benedito",
   "174":"Alfredo Freire II",
   "3":"Santa Maria"
   }

var opts = "";
for(var chave in obj) {
   opts += '<option value="'+chave+'">'+obj[chave]+'</option>';
}

var sel = document.body.querySelector("select");
sel.innerHTML = opts;

var sel_opts = Array.apply(null, sel.childNodes);

sel_opts.sort(function(a,b) {
    return a.text.localeCompare(b.text);
});

opts = "";
for(var chave of sel_opts) {
   opts += chave.outerHTML;
}

sel.innerHTML = opts;
<select>
</select>
    
24.03.2018 / 03:24
4

Unlike Arrays, an Object has no obligation to keep the order of the keys.

If you want to keep the order of items, you should send an array.

var json = [
  { key: "6", value: "Abadia" },
  { key: "218", value: "Abel Reis" },
  { key: "44", value: "Alexandre Campos - Jardim"  },
  { key: "13", value: "Alfredo Freire I"  },
  { key: "174", value: "Alfredo Freire II" },
  { key: "186", value: "Alfredo Freire III" },
  { key: "217", value: "Alfredo Freire IV" },
  { key: "189", value: "Alvorada I, Jardim" }
]

console.log(JSON.stringify(json, null, "  "))
    
23.03.2018 / 20:18