简体   繁体   中英

Access Object Properties in JavaScript JSON

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!

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." 
    }            
}

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

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." }

    }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM