Mouette
Mouette

Reputation: 299

Increment multiple nested variables in an object in Javascript

I have would like to increment multiple nested variables in an object:

My variable looks like this

var my_var = {
    count1 : 0,
    count2 : 0,
    count3 : 0
}

Currently i'm doing it this way:

my_var.count1 ++;
my_var.count2 ++;
my_var.count3 ++;

Is it a way to do something like this?

myvar : {
    count1++,
    count2++,
    count3++
}

Upvotes: 1

Views: 212

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

Is it a way to do something like this?

No reasonably, no, the way you're doing it is probably your best option.

You could use Object.keys and forEach:

Object.keys(my_var).forEach(function(key) {
    if (key.startsWith("count")) { // Or `if (/^count\d$/.test(key)) {`, or `if (/^count\d+$/.test(key)) {` if they can have multiple digits
        my_var[key]++;
    }
});

...but I'm not saying that's a good idea, unless there are factors not given in the question (a hundred count vars, or a run-time determined number of them, etc.).

Upvotes: 5

Related Questions