My code:
var a = "1",
b = "hello",
c = { "100" : "some important data" },
d = {};
d[a]["greeting"] = b;
d[a]["data"] = c;
console.debug (d);
I get the following error:
Uncaught TypeError: Cannot set property ‘greeting’ of undefined.
I’m trying to do something similar to an associative array. Why isn’t this working?
you never set
d[a]to any value.Because of this,
d[a]evaluates toundefined, and you can’t set properties onundefined.If you add
d[a] = {}right afterd = {}things should work as expected.Alternatively, you could use an object initializer:
Or you could set all the properties of
din an anonymous function instance:If you’re in an environment that supports ES2015 features, you can use computed property names: