Guesser
Guesser

Reputation: 1857

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

selected[year]=true;

Upvotes: 0

Views: 108

Answers (2)

Craig Morgan
Craig Morgan

Reputation: 962

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

var year=2103;
var month=9;

var selected=[];

selected[year]=[];

selected[year][month]=true;

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71908

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;

Upvotes: 5

Related Questions