Cannot set property for object
var data = {};
....
data[someprop][someotherprop] = 'bla bla'
I get
Uncaught TypeError: Cannot read property ... of undefined
and Cannot set property of...
Yes, the object does not have these properties..yet, but I am setting them on this line where I get the lol error. So what's with that?
source to share
if someprop
u someotherprop
are variables, Richard D's answer is correct, if they are hardcoded strings you can write your code like this:
var data = {someprop:{someotherprop: 'value'}};
if, however, they are values stored in variables, and you really - really want to slice everything into one line, try something like this:
var data = {window.someprop : {window.someotherprop: 'value'}};
where the window can be replaced by any object as long as the value is someprop
itself a property of the object:
var data = {someForm.name : { formElement.name : formElement.value}};
Or jQuery objects, as your tag suggests you use jQuery:
var data= {$('#formId').attr('name'):{$('#formSelect').attr('name'): $('#formSelect').val()}};
Note: the jQuery example is not recommended as the ID selector is used twice in the same element. jQuery will scan the DOM tree twice, so you'd better store this element #formSelect
in a variable somewhere.
source to share
You are trying to assign a property to an object that does not exist, doing this statement is equivalent to
data.someprop.someotherprop
the parser will not automatically generate an data.someprop
error for you.
You must initialize someprop
data.someprop = {};
data['someprop']['someotherprop'] = 'gw ganteng';
source to share