最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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 ..

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 ..

Share Improve this question asked Feb 12, 2013 at 0:17 Ravi RamRavi Ram 24.5k21 gold badges86 silver badges119 bronze badges 3
  • Array of js objects... – Dom Commented Feb 12, 2013 at 0:21
  • Arrays in JavaScript have numerical indexes (keys). As soon as you shove a non-numerical "index" into it, it's no longer an array. – NullUserException Commented Feb 12, 2013 at 0:21
  • @NullUserException my mistake, I thought it was saying var arrTotals = [ {DistroTotal: "0.00"}, {coupons: 12}, {invoiceAmount: "14.96"} ] – Dom Commented Feb 12, 2013 at 0:29
Add a comment  | 

2 Answers 2

Reset to default 11

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;

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';
    }
}
发布评论

评论列表(0)

  1. 暂无评论