Reputation: 11545
I'm trying to set some object properties, but I get this error sometimes:
Uncaught TypeError: Cannot read property '4' of undefined
The code:
var obj = {};
obj['fields'][4]['name'] = value;
yes, 4 does not exist, but why it is not created?
Upvotes: 0
Views: 113
Reputation: 41832
Actually, it's telling you obj['fields']
is undefined. And no, it does not automatically create nesting for you.
var obj = {};
obj['fields'] = {};
obj['fields'][4] = {};
obj['fields'][4]['name'] = value;
When working with an object, if you are unsure whether or not it has it's nesting already (and you don't want to overwrite it if it does), you can do the following:
obj['fields'] = obj['fields'] || {}
obj['fields'][4] = obj['fields'][4] || {};
//etc
To check for undefined:
if(!obj['fields']){} // undefined returns falsey
//or
if('fields' in obj == false){} // notice you can't lead with ! here
//or
if(obj['fields'] === undefined){} // note the triple ===
Upvotes: 8
Reputation: 700152
Trying to read a non-existing property doesn't create it. The exact reason that you get an error is that trying to access fields
returns undefined
, and you can't access any properties from an undefined
value.
To set the value, you need to create all parents:
obj.fields = [];
obj.fields[4] = {};
obj.fields[4].name = value;
Upvotes: 0
Reputation: 238
You have to init the the properties first:
var obj = {};
obj['fields'] = new Array();
obj['fields'][4] = new Array();
obj['fields'][4]['name'] = value;
Upvotes: 1