How do I go through the following array using javaScript?

0

json

[  
   {  
      "idDisciplina":"1",
      "0":"1",
      "Nome":"Matematica",
      "1":"Matematica"
   },
   {  
      "idDisciplina":"11",
      "0":"11",
      "Nome":"Ciencia",
      "1":"Ciencia"
   }
]

script

 $.ajax({
     url: "includes/disciplina.php/",
     type: "POST",
     data: {
         id: id
     },
     success: function(json) {
         $("#idDiciplina").html("");
         console.log(json);

         $('#idDiciplina').append("<option value='' selected='selected'>Disciplinas</option>");

         for (var i = 0; i < json.length; i++) {
             $('#idDiciplina').append("<option value=" + json[0][i] + ">" + json[1][i] + "</option>");

         }

     }

 });
    
asked by anonymous 25.08.2017 / 17:44

2 answers

2

The most semantic way is to use .reduce() . So you go through this array and you're adding content to an HTML string and in the end you only need to touch the DOM 1 time, directly with .html() to delete previous content and insert the whole all at once.

var json = [{ "idDisciplina": "1", "0": "1", "Nome": "Matematica", "1": "Matematica" }, { "idDisciplina": "11", "0": "11", "Nome": "Ciencia", "1": "Ciencia" }, { "idDisciplina": "12", "0": "12", "Nome": "Geologia", "1": "Geologia" }];

var html = json.reduce(function(string, obj) {
  return string + "<option value=" + obj.idDisciplina + ">" + obj.Nome + "</option>"
}, "<option value='' selected='selected'>Disciplinas</option>");

$("#idDiciplina").html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="idDiciplina"></select>

var json = [{
  "idDisciplina": "1",
  "0": "1",
  "Nome": "Matematica",
  "1": "Matematica"
}, {
  "idDisciplina": "11",
  "0": "11",
  "Nome": "Ciencia",
  "1": "Ciencia"
}, {
  "idDisciplina": "12",
  "0": "12",
  "Nome": "Geologia",
  "1": "Geologia"
}];
    
25.08.2017 / 18:15
1

You could do:

for (i=0 ; i<json.json.length ; i++){
     var idDisciplica = json.json[i].idDisciplina;
}
    
25.08.2017 / 17:47