I know this might be a noob question and that there are a lot of similar named questions but I couldn't find a solution which solved my problem.
I'm trying to access a simple nested JS object with the following code:
var test = '99999999';
var test_object = {};
test_object[test] = {"ak1" : "v1", "ak2" : "v2"};
console.log(test_object);
console.log(test_object.test);
But for some reason I keep getting 'undefined' when trying to access the 'test' property.
I've created a simple fiddle here: https://jsfiddle.net/nga7zqkf/
I just can't figure out why I can't access the 'test' property. Can someone please help me out here a bit?
Thanks!
var test = '99999999'; test_object[test] = {"ak1" : "v1", "ak2" : "v2"};
You never set the test property, you set the 99999999 property.
If you want to set the test property with square bracket notation, then the expression between [
and ]
has to evaluate as "test"
.
test_object["test"] = {"ak1" : "v1", "ak2" : "v2"};
Or
var test = 'test';
test_object[test] = {"ak1" : "v1", "ak2" : "v2"};
Please check below example
var test = 99999999;
var test_object = {};
var test_object2 = {};
test_object[test] = {"ak1" : "v1", "ak2" : "v2"};
console.log(test_object);
console.log(test_object[test]);
test_object2.test = {"ak1" : "v1", "ak2" : "v2"};
console.log(test_object2);
console.log(test_object2.test);
Working example link https://jsfiddle.net/nga7zqkf/3/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.