Selecting a Specific Value in Array Jquery

2

Hello, good morning! I am a beginner in the field and would like (if possible) help in resolving an issue.

The user will have a field to select the cities, when selecting, the system will capture the chosen city and will query a database to associate with a certain ID.

It turns out that when it selects one of the city options today, the system lists all possible cities and all other states.

I would like it to go into the array, do a validation of UF == es and then present only the chosen city with the validated UF (refine the options).

    
asked by anonymous 24.11.2017 / 13:26

2 answers

0

Since the existence test is based on the id you can use map to catch it only the id and indexOf. This gives -1 if it does not exist or a positive index when it exists.

//Essa é a lista

var arrayList = JSON.parse('[{"id":"1","name":"Fortaleza","uf":"CE"}]'); 

//funcao para gerar o objeto
function Employee(id, name, uf) {
    this.id = id;
    this.name = name;
    this.uf = uf;
}

//detectando click no botao
// e obtendo os dados
$( ".btn" ).click(function() {
  var id = $(this).data("id").toString();
  var name = $(this).data("name");
  var uf = $(this).data("uf");
  
  //criando objeto
  var employeeObject1 = new Employee(id,name, uf);
  
  
  let index = arrayList.map(x=>x.id).indexOf(id); //apanhar o indice com map e indexOf
  if (index === -1){ 
    document.getElementById("cidades").innerHTML = "Não existe na lista";
  }
  else { 
    document.getElementById("cidades").innerHTML = "Existe na lista";
  }

  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonclass="btn" data-id="1" data-name="fortaleza" data-uf="/CE">Selecionar cidade 1</button>

<button class="btn" data-id="2" data-name="São Paulo" data-uf="SP">Selecionar cidade 2</button>

<button class="btn" data-id="3" data-name="Rio de janeiro" data-uf="RJ">Selecionar cidade 3</button>



<div id="cidades"></div>
    
24.11.2017 / 13:43
0

Good morning,

A simple solution would be to iterate in this array of cities and create a new one, with only ES filtered cities.

var cidadesES = new Array();
cidade.forEach(function(obj) {
    if (obj.uf === "ES") {
        cidadesES.push(obj);
    }
});

The result would be a new array, which you can use in the selection field. I hope you have helped.

    
24.11.2017 / 13:43