Javascript how to put an associative array in another array?

1

Well, that puts an associative array under the form.

var tabla[];
tabla['nombre']='Jose';   

my code is as follows:

var regs = [];
var usuario = [];
usuario['nombre'] = 'Jose';
usuario['dni'] = '45875458X';
regs[0] = usuario;

usuario['nombre'] = 'Fernando';
usuario['dni'] = '52487125G';
regs[1] = usuario;
var sx = regs[0].nombre;
var sy = regs[1].nombre;

console.log(sx);
console.log(sy);

When I show the data it turns out that the two registers in the regs array are identical, I have given it a thousand laps and I only get it with an array of objects

    
asked by Pedro Robles Ruiz 12.01.2018 в 19:31
source

4 answers

2

The variable usuario , I have changed it to a function that receives the parameters nombre and dni . This function, what it does is declare an array, and then add the corresponding properties.

Then, using the function push , add to the end of the list reg , each user, calling the function usuario .

function usuario(nombre,dni)
{
    var array=[]
    array.nombre=nombre
    array.dni=dni
    return array
}
var regs = []
regs.push( usuario('Jose'    ,'45875458X') )
regs.push( usuario('Fernando','52487125G') )
var sx = regs[0].nombre
var sy = regs[1].nombre
console.log(sx)
console.log(sy)
console.log(regs)
    
answered by 12.01.2018 / 20:15
source
1

In JavaScript there are no associative arrays, they are called Objects. The MDN guide explains very well how to use them and the different methods they have. To create an object, you can do:

const usuario = {};
usuario.nombre = 'Jose';

Or directly define the properties of the object in its own definition using:

const usuario = {
  nombre: 'Jose',
  dni: '45875458X',
  ...
};

Next, you can access these properties using usuario.nombre or usuario['dni'] , which allows access to dynamic keys.

Another thing, instead of adding objects to an array by index, you can also use array.push(objeto) that will insert the object in the last position.

    
answered by 12.01.2018 в 19:41
1

As follows:

var array = {
  primero:{
    propiedad:"primer_valor1",
    propiedad2:"primer_valor2"
  },
  segundo:{
    propiedad:"segundo_valor1",
    propiedad2:"segundo_valor2"
  }
};
console.log(array);
console.log(array.primero.propiedad);
console.log(array.segundo.propiedad2);
    
answered by 12.01.2018 в 19:46
1

I hope you get the following code:

 usuarios = [];
    
    usuarios.push({
      nombre: 'Jose',
      dni: '45875458X'
    });
    
    usuarios.push({
      nombre: 'Fernando',
      dni: '52487125G'
    });
    
    console.log(usuarios);
    console.log(usuarios[0]);
    console.log(usuarios[0].nombre + ', tiene el DNI: ' + usuarios[0].dni);
    
answered by 12.01.2018 в 19:59