Create and browse an array in jquery with foreach?

0

How can you create a multidimensional array that contains keys and then traverse it with foreach.

It's because I have an array with data in php and I want to return it with ajax to jquery.

I have this and it does not work. And I want to do it with foreach ();

var persona = [
  var persona1 = ["nombre"=>"Luis","Edad"=>"32"],
  var persona2 = ["nombre"=>"Alex","Edad"=>"27"]

]
for(var i=0;i<persona.length;i++){
 alert(persona[i]["nombre"]);
}
    
asked by bsg 04.04.2017 в 18:46
source

2 answers

1

Your syntax is wrong, to declare the fix personas you should do so

var persona = [
  persona1 = {"nombre": "Luis","Edad": "32"},
  persona2 = {"nombre": "Marcos","Edad": "15"},
]

And there your for would work perfect, but if you still want to do it with a foreach I leave you a working Snippet:

var personas = [
  persona1 = {"nombre": "Luis","Edad": "32"},
  persona2 = {"nombre": "Marcos","Edad": "15"},
]


personas.forEach(function(persona, index) {
  console.log("Persona " + index + " | Nombre: " + persona.nombre + " Edad: " + persona.Edad)
});

I hope I have been helpful. Greetings!

    
answered by 05.04.2017 / 17:33
source
1

The simplest foreach statement in JS is:

for(var i in personas){
    console.log(personas[i].nombre);
}

However, the correct way to build objects is with the {} keys, since with [] you indicate an array . To build your objects there are two ways:

  • Direct assignment:

    var personas = [
      persona1 = {"nombre":"Luis","Edad":"32"},
      persona2 = {"nombre":"Alex","Edad":"27"}
    ]
    

    or just

    var personas = [
      {"nombre":"Luis", "Edad":"23"},
      {"nombre":"Alex", "Edad":"27"}
    ]
    
  • Definition (of object):

    function Persona(nombre, edad){
      this.nombre = nombre;
      this.edad = edad;
    }
    
    var personas = [new persona("Luis", 32), new persona("Alex", 27)];
    
    for(pers in personas){
      console.log(pers.nombre);
    }
    

I leave you a small POO tutorial in JavaScript so that you clarify your doubts.

    
answered by 05.04.2017 в 17:53