bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

Adding dynamically to multidimensional array javascript?

var oparea = [];
var mainarr_index = 0;

$("input.oparea-name").each(function(opera_key) {                                  
    var name_oparea = $(this);
    oparea[mainarr_index]['maincat']['name'] = name_oparea.val(); //Add to array

    $(subcats).each(function(index) { 
        oparea[mainarr_index]['subcat']['name'].push(name_subcat);
    }

    mainarr_index++;
}

The result I want:

oparea[0]['maincat']['name'] = 'name of oparea1';
oparea[0]['maincat']['subcat'] = array('name' => array('subcatname1', 'subcatname2'));

oparea[1]['maincat']['name'] = 'name of oparea2';
oparea[1]['maincat']['subcat'] = array('name' => array('subcatname1', 'subcatname2'));

//etc etc

The result I get in console is:

Uncaught TypeError: Cannot read property 'maincat' of undefined

Of course it's undefined, therefore I want to define it ;-)

How can I achieve what I want?

Upvotes: 0

Views: 45

Answers (2)

Barmar
Barmar

Reputation: 782785

You can't set the property of an object if there's no object there to begin with. And you can't push onto an array if the array hasn't been created yet (I suspect you're used to PHP, which will fill these things in automatically when necessary).

And you can use .push to add the new object to the array, instead of using the oparea_index variable.

$("input.oparea-name").each(function(opera_key) {                                  
    var name_oparea = $(this);
    var new_oparea = {
        maincat: {
            name: name_oparea.val()
        },
        subcat: {
            name: []
        }
    };

    $(subcats).each(function(index) { 
        new_oparea.subcat.name.push(name_subcat);
    }

    oparea.push(new_oparea);
}

Upvotes: 2

Duang
Duang

Reputation: 11

var oparea = [];
$("input.oparea-name").each(function(opera_key) {                                  
    var name_oparea = $(this);
    if(!oparea[mainarr_index]){
        oparea[mainarr_index]={};
    }
    if(!oparea[mainarr_index]['maincat']){
        oparea[mainarr_index]['maincat']={};
    }
    oparea[mainarr_index]['maincat']['name'] = name_oparea.val(); //Add to array

    $(subcats).each(function(index) { 
        if(!oparea[mainarr_index]){
            oparea[mainarr_index]={};
        }
        if(!oparea[mainarr_index]['subcat']){
            oparea[mainarr_index]['subcat']={};
        }
        if(!oparea[mainarr_index]['subcat']['name']){
            oparea[mainarr_index]['subcat']['name']=[];
        }
        oparea[mainarr_index]['subcat']['name'].push(name_subcat);
    }
}

Upvotes: 1

Related Questions