简体   繁体   中英

How to push onto a multidimensional associative array

I'm looping through some HTML form elements on a page like so.

var itemsArray = new Array();
$('input[type="text"].qty').each(function(index) {
    if($(this).val()) {
        itemsArray[index]['qty'] = $(this).val();
        itemsArray[index]['itemPrice'] = $(this).parents('.control-group').find('.itemPrice').val();
        itemsArray[index]['itemID'] = $(this).parents('.control-group').find('.itemID').val();
    }
});

The index i'm hoping to be 0,1,2,3 etc.. like a regular array. With the sub elements being associative and assigned to various values.

I'm getting this error in the console.

TypeError: itemsArray[index] is undefined

You need to make sure each item in the outer array is initialized before you start using it. Note, I changed to object notation below just for clarity.

$('input[type="text"].qty').each(function(index) {
    if($(this).val()) {
        itemsArray[index] = {};
        itemsArray[index].qty = $(this).val();
        itemsArray[index].itemPrice = $(this).parents('.control-group').find('.itemPrice').val();
        itemsArray[index].itemID = $(this).parents('.control-group').find('.itemID').val();
    }
});

Consider using an array of objects. Arrays in Javascript are not really intended to be used in the way you are (the multidimensional part). Also itemsArray = [] is preferred over new Array() .

var itemsArray = [];
$('input[type="text"].qty').each(function(index) {
    if($(this).val()) {
        itemsArray.push({
            qty : $(this).val(),
            itemPrice :  $(this).parents('.control-group').find('.itemPrice').val(),
            itemID : $(this).parents('.control-group').find('.itemID').val()
        });

    }
});

It means what it says. itemsArray[index] is undefined , and you cannot assign properties on this. Notice that you don't have a "multidimensional array", but just an array of objects. For each new index , you will need to create a new object.

var $this = $(this);
if ($this.val()) {
    var $parent = $(this).parents('.control-group'); // .closest() should suffice
    itemsArray[index] = {
        qty: $this.val(),
        itemPrice: $parent.find('.itemPrice').val(),
        itemID: $parent.find('.itemID').val()
    };
}

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