我在javascript中更新了一个数组(key,value)对象

Rav*_*Ram 4 javascript arrays

如何更新数组(键,值)对象?

arrTotals[
{DistroTotal: "0.00"},
{coupons: 12},
{invoiceAmount: "14.96"}
]
Run Code Online (Sandbox Code Playgroud)

我想将'DistroTotal'更新为值.

我试过了

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

谢谢 ..

Dan*_*mer 7

因为听起来你正在尝试使用键/值字典.考虑在此处切换到使用对象而不是数组.

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

arrTotals["DistroTotal"] = 2.00;
Run Code Online (Sandbox Code Playgroud)


Exp*_*lls 6

您错过了嵌套级别:

for (var key in arrTotals[0]) {
Run Code Online (Sandbox Code Playgroud)

如果您只需要使用特定的那个,那么只需:

arrTotals[0].DistroTotal = '2.00';
Run Code Online (Sandbox Code Playgroud)

如果你不知道带有DistroTotal密钥的对象在哪里,或者有很多对象,你的循环就会有所不同:

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