Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I update an array (key,value) object in javascript

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

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

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

I have tried

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

Thanks ..

like image 550
Ravi Ram Avatar asked Dec 05 '22 12:12

Ravi Ram


2 Answers

Since it sounds 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;
like image 54
Dan Saltmer Avatar answered Jan 01 '23 14:01

Dan Saltmer


You're missing a level of nesting:

for (var key in arrTotals[0]) {

If you only need to work with that specific one, then just do:

arrTotals[0].DistroTotal = '2.00';

If you don't know where the object with the DistroTotal key is, or there are many of them, your loop is a bit different:

for (var x = 0; x < arrTotals.length; x++) {
    if (arrTotals[x].hasOwnProperty('DistroTotal') {
        arrTotals[x].DistroTotal = '2.00';
    }
}
like image 26
Explosion Pills Avatar answered Jan 01 '23 16:01

Explosion Pills