简体   繁体   中英

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?

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);
}
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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM