Selecting a Specific Value in Jquery Array

Asked

Viewed 114 times

2

Hello, good morning, good morning! I am beginner in the area and would like to (if possible) help to resolve an issue.

The user will have a field to select the cities, when selecting, the system will capture the chosen city and will make a query to a database to associate to 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 enter the array, make a validation of UF == es and then present only the chosen city with the validated UF (refine the options).

inserir a descrição da imagem aqui

  • Edit your post include code in text form.

2 answers

0

Since the existence test is based on id you can use map to catch only id and index. This gives -1 if there is no or a positive index when there is.

//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>
<button class="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>

0

Good morning,

A simple solution would be to iterate in this array of cities and create a new one, only with 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 it helped.

Browser other questions tagged

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