JavaScript - cannot set undefined property

My code is:

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: Unable to set the greeting property to undefined.

I am trying to do something similar to an associative array. Why is this not working?

+72
javascript
Sep 20 2018-11-11T00:
source share
4 answers

you never set d[a] to any value.

Because of this, d[a] evaluates to undefined , and you cannot set properties to undefined .

If you add d[a] = {} immediately after d = {} , everything should work as expected.

Alternatively, you can use the object initializer:

 d[a] = { greetings: b, data: c }; 

Or you can set all the properties of d in an instance of an anonymous function:

 d = new function () { this[a] = { greetings: b, data: c }; }; 



If you are in an environment that supports ES2015 features, you can use the names of the calculated properties :

 d = { [a]: { greetings: b, data: c } }; 
+95
Sep 20 '11 at 2:45
source share

You must set d[a] either an associative array or an object:

  • d[a] = [];
  • d[a] = {};



Without customization, this is what happens:

d[a] == undefined , so you do undefined['greeting']=b; and by definition, undefined has no properties. Thus, the error you received.

+20
Sep 20 2018-11-11T00:
source share

The object stored in d[a] is not configured for anything. Thus, d[a] is evaluated as undefined . You cannot assign an undefined :) property. You need to assign an object or an array d[a] :

 d[a] = []; d[a]["greeting"] = b; console.debug(d); 
+4
Sep 20 2018-11-11T00:
source share

In javascript, almost all objects, null and undefined are the exception.

Array instances are an object. therefore you can set the property of an array, for the same reason you cannot set the property undefined because its NOT object

+3
Sep 20 '11 at 3:40
source share



All Articles