how do I pass a json to an array in Jquery

0

I have a little doubt, which is that I have to put a json to a array ,

My jquery:

function girar_ruleta() {
var mesa = $("#numero_unico").val();
$('#ruleta_giratoria').modal('show');
$.post("php/traer_madres.php", {mesa: mesa}, function (data) {
    var dato = $.trim(data);
    console.log(dato);
});

}

what returns me data

{"data":[{"nombre_completo":"YOLANDA MEJIA ROJAS"},{"nombre_completo":"IRMA VARA SANCHEZ"},{"nombre_completo":"DIANA AGUAYO MORENO"}]}

That I want to pass to an array.

Thank you.

    
asked by Joel More F. 11.05.2017 в 19:01
source

3 answers

-1

Iterate between the data with a for and add them to your arra with a push .

in your case it would be like this:

function girar_ruleta() {
    var mesa = $("#numero_unico").val();
    $('#ruleta_giratoria').modal('show');
    $.post("php/traer_madres.php", {mesa: mesa}, function (data) {
        //si tu data es un string agrega
        data=$.parseJSON(data);

        dato=[];
        for (element in data.data) { 
            dato.push(data.data[element]["nombre_completo"])
        };
        console.log(dato);
    });
 }

    data={"data":[{"nombre_completo":"YOLANDA MEJIA ROJAS"}, {"nombre_completo":"IRMA VARA SANCHEZ"},{"nombre_completo":"DIANA AGUAYO MORENO"}]}
dato=[];
for (element in data.data) { 
     dato.push(data.data[element]["nombre_completo"])
};
console.log(dato);
    
answered by 11.05.2017 / 19:21
source
0

To be sure that you are returning a JSON, check php / bring_mothers.php to have something like this echo json_encode ($ answer); once you return to your front to access your answer, in this case data, you just have to do data ["data"] and with that you get the values. This also depends on how you are building your json in php, I also consider that var data = $ .trim (data); the structure of the object is affected.

Example php response

$datos[1]["nombre_completo"] = "YOLANDA MEJIA ROJAS";
$datos[2]["nombre_completo"] = "IRMA VARA SANCHEZ";
$respuesta = array("data"=>$datos);

echo json_encode($respuesta);

In your js you would receive in this way.

function girar_ruleta() {
var mesa = $("#numero_unico").val();
$('#ruleta_giratoria').modal('show');
$.post("php/traer_madres.php", {mesa: mesa}, function (data) {
    $.each(data["data"], function(i, persona) {
            alert(persona.nombre_completo);
    });
});

}
    
answered by 11.05.2017 в 21:39
0

Just pass the response of your service to arrays in this way:

var arr = Object.values(response)
    
answered by 11.05.2017 в 22:35