user6427229
user6427229

Reputation:

Increment value of a property when value isn't defined

I'm trying to add assign a value to a property in this fashion, but I can't seem to figure out how I could do this the correct way

let test = {}
test["Hi"] = 0 // would be inside a loop, so unless I add a check to see if "Hi" is a valid key in the object
test["Hi"] += 1 // What I want to happen

let test2 = {} // what I thought would work
test2["Hi"] += 1 || 0

console.log(test2) -- {Hi: NaN}

Upvotes: 0

Views: 39

Answers (2)

hygull
hygull

Reputation: 8740

@leak, currently I will suggest you to use the below approach. Later, I will think about your approach and update the answer.

Please comment if you have any suggestions for the improvement.

var test2 = {};
test2["Hi"] = test2["Hi"] != undefined? test2["Hi"] + 1:0
console.log(test2) //{Hi: 0};

test2["Hi"] = test2["Hi"] != undefined? test2["Hi"] + 1:0
console.log(test2) //{Hi: 1};

test2["Hi"] = test2["Hi"] != undefined? test2["Hi"] + 1:0
console.log(test2) //{Hi: 2};

Upvotes: 0

Yosef Tukachinsky
Yosef Tukachinsky

Reputation: 5895

with test2["Hi"] += 1 || 0 what you ask to do is: if you can put to test2["Hi"] the value (test2["Hi"]+1) - do it. else, put there the value of test2["Hi"]+0. in your case, test2["Hi"] is undefined, so both of the options return NaN. if what you whant to do is test2["Hi"]+= 1 OR test2["Hi"] = 0, you can do it in another ways,

like:

    test2["Hi"] = test2["Hi"] + 1 || 0;

OR

    test2["Hi"] = test2["Hi"] ? test2["Hi"] += 1 : 0;

as you prefer. hope its help

Upvotes: 1

Related Questions