How to create an array inside another array with jQuery

5

I'm trying to create a array in jQuery using the .push () function where each element should contain another array inside it. The framework I need to create is this:

 
array(
    'elemento1' => array(
        'elemento1' => 'dado1',
        'elemento2' => 'dado2'
    ),
    'elemento2' => array(
        'elemento1' => 'dado1',
        'elemento2' => 'dado2'
    ),
    'elemento1' => array(
        'elemento1' => 'dado1',
        'elemento2' => 'dado2'
    ),
) 

My intention is to generate a list of information with the invoices of an NF-e, where each invoice will have its invoice number, expiration date and its value. With this I want to generate an array in jquery to pass via ajax as parameter and in the php file, do all the processing to be written in mysql. That's basically it.

How to proceed?

    
asked by anonymous 15.05.2015 / 20:22

3 answers

1

SOLUTION
The solution I found was this: link

    
19.05.2015 / 20:45
5

There are several ways. The closest to the code that you put (which is PHP, right?), Are nested literal objects (if the keys have names), or nested arrays (numeric keys).

Nested literal objects

var obj = {
    'elemento1' : {
        'elemento1' : 'dado1',
        'elemento2' : 'dado2'
    },
    'elemento2' : {
        'elemento1' : 'dado1',
        'elemento2' : 'dado2'
    },
    'elemento1' : {
        'elemento1' : 'dado1',
        'elemento2' : 'dado2'
    },
};

Nested literal arrays

var arr = [
    ['dado1','dado2'],
    ['dado1','dado2'],
    ['dado1','dado2']
];

Or maybe you want a combination of the two, as in Eduardo Nobre's answer .

Using push

Since you quoted push in the question, here are some examples with this method:

// Primeiro você cria a array, depois dá push dos valores
var a = [];
a.push('dado1', 'dado2');

// O resultado é o mesmo de usar arrays literais:
var b = ['dado1','dado2'];
var c = ['dado1','dado2'];

// Embrulhando tudo em outra array
var arr = [];
arr.push(a, b, c);

Note: arrays are not jQuery, they are part of the JavaScript language (in which jQuery is written).

    
15.05.2015 / 20:28
1

You can do something like this:

var options = { 
    size: ["S", "M", "L", "XL", "XXL"],
    color: ["Red", "Blue", "Green", "White", "Black"]
};

To access each key individually:

for (var key in options) {
    alert(key);
}
    
15.05.2015 / 20:27