0

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 because the first key has not been created and Javascript is not automatically doing that.

selected[year]=true;

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

Comments

0

You just need to add a step: selected[year]=[];

var year=2103;
var month=9;

var selected=[];

selected[year]=[];

selected[year][month]=true;

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.