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?

+3


source to share


5 answers


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.

+1


source


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';

      

+6


source


You need to set properties using the following steps:

var data = {};


data[someprop] = {}; 
data[someprop][someotherprop] = 'bla bla';

      

The object data will not have a property named "someprop" before you edit it.

+3


source


var data = {};
data[someprop] = {someotherprop:'bla bla'};

      

otherwise it data[someprop]

will be undefined

+3


source


First you need to create data[someprop]

:

var data = {};
data[someprop] = {};
data[someprop][someotherprop] = 'bla bla'

      

http://jsfiddle.net/infernalbadger/zXETB/

+1


source







All Articles