Snuur
Snuur

Reputation: 309

creating nested array javascript

Have looked at many examples but cant seem to get to make an nested array to store some data nicely. How can I get the following code to work? It gives me an error now:

var shipdata = [];

shipdata['header']['bedrijfsnaam'] = $('[name="bedrijfsnaam"]').val();
shipdata['header']['naam'] = $('[name="naam"]').val();
shipdata['header']['straat'] = $('[name="straat"]').val();
shipdata['header']['postcode'] = $('[name="postcode"]').val();
shipdata['header']['plaats'] = $('[name="plaats"]').val();
shipdata['header']['telefoon'] = $('[name="telefoon"]').val();
shipdata['header']['email'] = $('[name="email"]').val();
shipdata['header']['instructies'] = $('[name="instructies"]').val();
shipdata['header']['ordernummertje'] = $('[name="ordernummertje"]').val();

$(".pakketten").each(function(index, element) {

            index++;
            shipdata['pakketten']['pakket'+index]['lengte'] = $('[name="lengte'+index+'"]').val(),
            shipdata['pakketten']['pakket'+index]['breedte'] = $('[name="breedte'+index+'"]').val(),
            shipdata['pakketten']['pakket'+index]['hoogte'] = $('[name="hoogte'+index+'"]').val(),
            shipdata['pakketten']['pakket'+index]['gewicht'] $('[name="gewicht'+index+'"]').val()


        });

Probably im doing this all wrong, but some pointers would be welcome.

Thanks!

Upvotes: 1

Views: 113

Answers (2)

antyrat
antyrat

Reputation: 27765

You need to create objects each time you want to have nested array:

var shipdata = {};
shipdata['header'] = {};
shipdata['header']['bedrijfsnaam'] = $('[name="bedrijfsnaam"]').val();
//...

shipdata['pakketten'] = {};

$(".pakketten").each(function(index, element) {

    index++;
    shipdata['pakketten']['pakket'+index] = {};
    shipdata['pakketten']['pakket'+index]['lengte'] = $('[name="lengte'+index+'"]').val(),
    // ...

Answer updated due to comments as arrays didn't have string indexes.

Upvotes: 2

Sirko
Sirko

Reputation: 74086

First of all, you are creating an object and not an array, so use {} instead of [] for the main container.

Second, when inserting multiple values at the same time, you can use a much more compact notation:

var shipdata = {
  'header': {
    'bedrijfsnaam': $('[name="bedrijfsnaam"]').val(),
    'naam': $('[name="naam"]').val()
    '...': '...'
  },
  'pakketten': []
};

$(".pakketten").each(function(index, element) {
            shipdata['pakketten'].push({
              'lengte': $('[name="lengte'+index+'"]').val(),
              'breedte': $('[name="breedte'+index+'"]').val(),
              '...': '...'
            });
});

Besides, anytime you want to access an object or array in any way, you have to initialize it beforehand as already mentioned by @antyrat.

Upvotes: 4

Related Questions