0

I have the following json data:

 {
      "324": "Aguacate",
      "196": "Fresa",
      "7875": "Mandarina",
      "197": "Platano",
      "9517": "Uvas"
 }

For any reason, when I populate the target select dropdown's options, it returns the options in a different order (by ID):

 {
      "196": "Fresa",
      "197": "Platano",
      "324": "Aguacate",
      "7875": "Mandarina",
      "9517": "Uvas"
 }

Considering that the script looks like:

  $.getJSON("http://path/to/blabla.json", customfunction);

  function customfunction(data) {

        var $select = $('#mymail_data_socio'); 

        // First, empty the select field
        $select.find('option').remove();

        $.each(data,function(key, value) {
              $select.append('<option value=' + key + '>' + value + '</option>');
        });

  }

Is there any way to return the options in the same order as in my json file? How I should rewrite my script in order to achieve it?

Thanks!

Capiedge
  • 216
  • 2
  • 10

2 Answers2

2

This is a browser specific issue (basically chrome issue), where the browser javascript engine loops through the object properties in order (numeric properties) : https://bugs.chromium.org/p/v8/issues/detail?id=164

You can use a prefix and then replace it in the loop as follows:

var obj = {
      "id_324": "Aguacate",
      "id_196": "Fresa",
      "id_7875": "Mandarina",
      "id_197": "Platano",
      "id_9517": "Uvas"
 };
 
 function customfunction(data) {

        var $select = $('#mymail_data_socio'); 

        // First, empty the select field
        $select.find('option').remove();

        $.each(data,function(key, value) {
              $select.append('<option value=' + key.replace('id_', '') + '>' + value + '</option>');
        });

  }
  
  customfunction(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mymail_data_socio"></select>
KAD
  • 10,375
  • 4
  • 25
  • 60
1

The other option is to use JSONArray and can be iterated with inner loop (can be quite hectic with more than one iteration) which will give the desired result with the same order specified.

here is the example with both ways

Nrzonline
  • 1,447
  • 2
  • 18
  • 33
Komal
  • 304
  • 1
  • 7