Javascript - Dynamic Object Keys (second Key)
I can create a dynamic object as follows: var year=2103; var month=9; var selected={}; selected[year][month]=true; But the following gives an undefined object error I presume bec
Solution 1:
But the following gives an undefined object error I presume because the first key has not been created and Javascript is not automatically doing that.
Yes, you have to create it:
var year = 2103;
var month = 9;
var selected = {};
selected[year] = {};
selected[year][month] = true;
If you're unsure if the object already exists, and do not want to overwrite it:
selected[year] = selected[year] || {};
As a shortcut to populate the object if missing & assign the month key in one step:
(selected[year]||(selected[year]={}))[month] = true;
Solution 2:
You just need to add a step: selected[year]=[];
var year=2103;
var month=9;
var selected=[];
selected[year]=[];
selected[year][month]=true;
Post a Comment for "Javascript - Dynamic Object Keys (second Key)"