How to capture the value of a key from a JSON (coming from an AJAX) using Jquery?

0

I have the following AJAX:

$("button[name='btn-editar-marca']").on('click', function(){
    $.ajax({
        type: "GET",
        url: "../ajax/ajax.marcas.php",
        data: {"ajax-params": 2, "Id_Marca": $(this).attr("id")},
        dataType: "JSON",
        success: function(res){
            console.log(res);
            $("input[name='inputCodMarca']").val(res.Id_Marca);
            $("input[name='inputNomeMarca']").val(res.Nome_Marca);
            $("input[name='textareaObsMarca']").val(res.Obs_Marca);
            $("input[name='inputDataCadMarca']").val(res.Data_Cadastro);
            $('#md-editar-marca').modal('show');
        },
        error: function(res){
            if(res.status == 200)
                alert("Erro 200");
            else if(res.status == 404)
                alert("Erro 404");
            else
                alert("Algo de errado não está certo!");
        }
    });
});

The console.log(res) on the middle shows the following return:

Whenyouopenit:

Whenyouopen"position [0]":

Thesevaluesthatappearedinposition0aretheonesIwanttocapturetoinsertthemintoinputs,Ievengetthemasfollows:

res[0].Id_Marcares[0].Nome_Marca

Isthistheonlywaytocapturevalues?Iwouldlikesomethingmore"professional", so to speak, some function, something like that, in that case, it is a select that only has 1 value (selectPorId), so it will only have position 0 same, but soon less I will have which bring more values, for example: "Select the items of a purchase". Often it will have more than 1 item, so it would have to be something dynamic. How could I replace this res[0].VALORES with something dynamic?

I have seen the JSON.parse() function but it did not work, maybe because I did not know how to use it or maybe it was not the ideal function for the case.

    
asked by anonymous 13.05.2018 / 18:25

1 answer

0

In case your array has more than 1 element you will need to use the .map () function or even a for example to go through your array:

res.map((i, j) => {
  console.log(res[j].Id_Marca)
  console.log(res[j].Nome_Marca)
});

So you do not have to worry about the size of your json's return.

    
16.05.2018 / 15:38