Iterate table in php in Javascript array

2

Hello, I have the following table that I am calling using a controller

Driver

$respuesta = GestorOITModels::obtenerViasModel("transporte"); //nombre de la tabla
$datos = array($respuesta);
echo json_encode($datos);

JS file, where I try to save the table

$(".content-wrapper").ready(function(){

    var vias;

    $.ajax({
        url: "views/ajax/OIT.php",
        method: "GET",
        dataType: "json",
        success: function(respuesta) {
            if (respuesta == 0) {
                console.log("malo");

            } else {
                vias=respuesta[0];
                console.log("Primer console", vias);
                vias.forEach( function(valor, indice, array) {
                    console.log("En el índice " + indice + " hay este valor: " + valor);});
            }
        }
    });
})

But when I use the browser console, it looks like this:

Data thrown using JSON.stringify (answer)

[[{"0":"AEREO","tipo":"AEREO"},{"0":"DIRECTO","tipo":"DIRECTO"},{"0":"MARITIMO","tipo":"MARITIMO"},{"0":"OTROS","tipo":"OTROS"},{"0":"TERRESTRE","tipo":"TERRESTRE"}]]

What do I have to correct so that when I iterate it again I would stay for example: "Via[0]="AEREO"-Via[1]="DIRECTO" , etc.

Thank you very much for the help.

    
asked by Baker1562 14.02.2018 в 08:36
source

1 answer

1

The problem you are having is that each element of the matrix is an object that has two properties with the same value, so if you try to show its content it will tell you that it is of type Object .

To show its content you must indicate the property you want to show, I add several examples of how to access each of them:

vias = [
  {0: 'AEREO', tipo: 'AEREO'},
  {0: 'DIRECTO', tipo: 'DIRECTO'},
  {0: 'MARITIMO', tipo: 'MARITIMO'},
];
console.log("Primer console", vias);
vias.forEach( function(valor, indice, array) {
  console.log(
    "En el índice " + indice +
    " hay este valor (propiedad 'tipo'): " + valor.tipo +
    " (desde ['tipo']): " + valor['tipo'] +
    " (desde [0]): " + valor[0]
  );
});
    
answered by 14.02.2018 / 08:40
source