I am updating an array object (key, value) in javascript

How can I update the array (key, value) object?

arrTotals[
{DistroTotal: "0.00"},
{coupons: 12},
{invoiceAmount: "14.96"}
]

      

I want to update the "DistroTotal" value to a value.

I tried

    for (var key in arrTotals) {
        if (arrTotals[key] == 'DistroTotal') {
            arrTotals.splice(key, 2.00);
        }
    }

      

Thank..

+3


source to share


2 answers


You are missing the nesting level:

for (var key in arrTotals[0]) {

      

If you only need to work with this particular one, just do:



arrTotals[0].DistroTotal = '2.00';

      

If you don't know where the keyed object is DistroTotal

, or there are many, your loop is slightly different:

for (var x = 0; x < arrTotals.length; x++) {
    if (arrTotals[x].hasOwnProperty('DistroTotal') {
        arrTotals[x].DistroTotal = '2.00';
    }
}

      

+6


source


Since it looks like you are trying to use a key / value dictionary. Consider switching to using an object instead of an array here.



arrTotals = { 
    DistroTotal: 0.00,
    coupons: 12,
    invoiceAmount: "14.96"
};

arrTotals["DistroTotal"] = 2.00;

      

+7


source







All Articles