Reputation: 2732
I am working on some basic object projects to get into using them and tying in JSON as well. However, I am missing something as I keep being returned 'undefined' when trying to access nested properties.
The goal is to create a new scene object and load the content based on the scene name I am passing.
function newScene(name) {
var sceneName = name;
this.sceneDetails = function() {
var theDetails = {
"home": [
{ "title": "Home Page",
"desc": "This home page is the homiest of all home pages." }
],
"about": [
{ "title": "The About Page",
"desc": "This page is about stuff." }
]
}
console.log(theDetails[sceneName]['title']);
}
}
var thePage = new newScene('home');
var thePageBuild = thePage.sceneDetails();
When running this I am given 'undefined' as opposed to the actual Home title. Any help would be greatly appreciated. Thank!
Upvotes: 0
Views: 63
Reputation: 629
Because you have home and about set to arrays, you need to access them like this:
console.log(theDetails[sceneName][0]['title']);
or restructure the json like this:
var theDetails = {
"home":
{ "title": "Home Page",
"desc": "This home page is the homiest of all home pages." },
"about":
{ "title": "The About Page",
"desc": "This page is about stuff." }
}
Upvotes: 0
Reputation: 3555
Try this
function newScene(name) {
var sceneName = name;
this.sceneDetails = function() {
var theDetails = {
"home": [
{ "title": "Home Page",
"desc": "This home page is the homiest of all home pages." }
],
"about": [
{ "title": "The About Page",
"desc": "This page is about stuff." }
]
}
console.log(theDetails[sceneName][0].title);
}
}
var thePage = new newScene('home');
var thePageBuild = thePage.sceneDetails();
This is the working fiddle
Upvotes: 0
Reputation: 1111
You are adding the title and description to an array, so the actual details are located at
console.log(theDetails[sceneName][0]['title']);
I'm suspecting this wasn't what you wanted, so change the theDetails assignment to this and the code should work just fine:
var theDetails = {
"home": {
"title": "Home Page",
"desc": "This home page is the homiest of all home pages."
},
"about": {
"title": "The About Page",
"desc": "This page is about stuff."
}
}
Upvotes: 1