I have this code:
var string = {
nameString : "nameValue",
nameString2 : "nameValue2",
nameString3 : "nameValue3",
datathing : 0,
};
var data = {
data : 1,
dataNum2 : 2,
dataNum3 : 3,
dataNum4 : 4,
};
var thing = {
datathing1 : 10,
datathing2 : 20,
datathing3 : 30,
datathing4 : 40,
};
var object = {
object1 : string,
data1 : data,
thing1 : thing,
};
Why do neither of these means to access the data work:
alert("testReference= " + object['object1']['string']['nameString']);
alert("testReference= " + object.object1.string.nameString);
I cannot understand it, even though similar examples found below and textbooks state explicitly that they should work:
Accessing nested JavaScript objects with string key
Thanks in advance for any input!
I am currently constructing an object and passing it around, a 'for in' will bring up the values but a 'typeof' test or any other way I try and access will not work, either I will encounter an error (which breaks the program, I think) or I get 'undefined'....
One last thing if this gets solved, is it ok to nest a key that is the same name value as its parent, such as data.data - this leads to the possibility of further nesting such as data.data.data...
Let's look at what's wrong with each example, then take a look at the way that works right.
Example 1
object['object1']['string']['nameString']
We expect
object['object1']
to return the objectstring
, right? So lets simplify the big expression by replacing that part of it. That'll make it easier for us to understand.So now we have
string['string']['nameString']
.But
string
has no member called 'string', sostring['string']
returnsundefined
.And when you try to treat
undefined
as an object, you get an error!Example 2
object.object1.string.nameString
We expect
object.object1
returns the objectstring
, right? So lets simplify the big expression by replacing that part of it. That'll make it easier for us to understand.So now we have
string.string.nameString
.But
string
has no member called 'string', sostring.string
returnsundefined
.And when you try to treat
undefined
as an object, you get an error!.What You Want
object.object1.nameString
(orobject['object1']['nameString']
)We expect
object.object1
returns the objectstring
, right? So lets simplify the big expression by replacing that part of it. That'll make it easier for us to understand.So now we have
string.nameString
, and we expect that to return"nameValue"
.And it does!