1

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++
}

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.