Query on Json file

-1

I am making a listing of cities and states via JSON . I always create a table in the database to return this information. But today I'm making it to the JSON file. The layout of the states file:

[{"ID": "1",
"Nome": "Afonso Cláudio",
"Estado": "8"
},
 {
"ID": "2",
"Nome": "Água Doce do Norte",
"Estado": "8"
},
 {
"ID": "3",
"Nome": "Águia Branca",
"Estado": "8"
},
 {
"ID": "4",
"Nome": "Alegre",
"Estado": "8"
}, etc]

What do I need and can not do, and return all cities that have the same value as the Estado key.

The query I perform as follows:

$.getJSON("<?php echo base_url();?>assets/admin/json/Cidades.json", {'Estado':2}, function(json) {
  var options = "<select name='cidade' id='cidade' class='form-control show-tick'>";
  $.each(json, function(key, value){
   options += '<option value="' + value.Sigla + '">' + value.Nome + '</option>';
  });
  options += '</select>';
  $("#selectCidades").html(options);            
});

So the way the filtering is done does not happen with the ID key entered. Note: the value 2 of the parameter informed and only of example, this value comes from a variable filled with select states

    
asked by anonymous 18.09.2017 / 03:58

1 answer

1

If you do the filtering on the server is better, because you already pass the information that Estado searches. But you can do this on the client, using .filter() , like this:

json = json.filter(obj => obj.Estado == 2)

An example would be:

const estado = 2;
$.getJSON("<?php echo base_url();?>assets/admin/json/Cidades.json", {'Estado': estado}, function(json) {
    const html = json.filter(obj => obj.Estado == estado).reduce((select, obj) => {
    return select + '<option value="' + value.Sigla + '">' + value.Nome + '</option>';
  }, "<select name='cidade' id='cidade' class='form-control show-tick'>") + "</select>";

  $("#selectCidades").html(html);
});
    
18.09.2017 / 07:17