Reputation: 398
I have a this._champ
object (which is undefined by default).
I browser an array, and want to add this field with a value : this._champ[champ.name][ele.infos[0].StackableRangeName] = ele.value;
but at the first iteration, [champ.name] is undefined
, and [ele.infos[0].StackableRangeName]
is always undefined
, how to manage this?
I tried this ternary operator but it isn't working:
this.champ[champ.name] != undefined ? this._champ[champ.name].push({ele.infos[0].StackableRangeName: ele.value}) : this._champ.push({champ.name: {ele.infos[0].StackableRangeName: ele.value}})
Upvotes: 0
Views: 642
Reputation: 781721
This is a common idiom for initializing something with a default value if it's not yet set:
this.champ[champ.name] = this.champ[champ.name] || []
Upvotes: 3
Reputation: 5488
Just check for existence of the key. and then push value:
if(this.champ && !this.champ.hasOwnProperty(champ.name)) {
this.champ[champ.name] = [];
}
this._champ[champ.name].push({ele.infos[0].StackableRangeName: ele.value});
Upvotes: 1