cicakman
cicakman

Reputation: 1990

jquery multidimensional array undefined

I need to create multi dimensional array in JavaScript

var collection = new Array();
$(document).on('change', 'input[type="checkbox"]', function(e) {
    if (this.checked) {
        var type = $(this).data('type');
        var id = $(this).data('id');

        collection[type].push(id);
    }
});

Uncaught TypeError: Cannot read property 'push' of undefined

I need to convert these values into JSON format later on.

Any idea how to fix this?

Upvotes: 0

Views: 404

Answers (3)

iLikePrograms
iLikePrograms

Reputation: 468

The reason that this is not working is that you are trying to push it into a multidimentional array, but the array you are attempting to push to doesnt exist.

var collection = [];
$(document).on('change', 'input[type="checkbox"]', function(e) {
    if (this.checked) {
        var type = $(this).data('type');
        var id = $(this).data('id');

        if (typeof collection[type] === 'undefined') {
            collection[type] = [];
        }

        collection[type].push(id);
    }
});

That should work. Just so you know, it is much better to use [] instead of new Array(). As calling new Array() can have very strange behavior and can be confusing for beginners, for the most part stick with `[].

Also i have added if (typeof collection[type] === 'undefined') {
What this will do is check if the index inside the collection array is undefined. If it is, that means there is no array to push the id to. So we create the array of the type inside collection with the line below it:

collection[type].push(id);

Hope that makes sense to you, I remember multimentional arrays being confusing too!!

Upvotes: 1

Krzysiek
Krzysiek

Reputation: 2495

You have to define array:

//var collection = new Array(); //for array index must be ineger
var collection = {}; //for not numeric indexes
$(document).on('change', 'input[type="checkbox"]', function(e) {
    if (this.checked) {
        var type = $(this).data('type');
        var id = $(this).data('id');
        if('array' !== typeof collection[type]) collection[type] = new Array();
        collection[type].push(id);
    }
});

Upvotes: 1

chridam
chridam

Reputation: 103335

You could create an an object which is more appropriate in this case:

var collection = {};
$(document).on('change', 'input[type="checkbox"]', function(e) {
    if (this.checked) {
        var type = $(this).data('type');
        var id = $(this).data('id');

        if (!collection[type]) {
           collection[type] = [];
        }
        collection[type].push(id);
    }
});   

Upvotes: 1

Related Questions