Zeng Cheng
Zeng Cheng

Reputation: 825

JSON - JavaScript get nested value

Let's say I have this in JavaScript object taken from a Firebase query.

{
    "player": {
        "player:616320": {
            "skills": {
                "main": {
                    "attack": 1,
                    "defence": 1
                }
            },
            "uid": "player:616320",
            "username": "test1",
            "x": 1,
            "y": 1
        }
    }
}

var data = snap.val();

I can do data.username to get test1... but how would I go further? I tried searching JSON nesting and ... it was complicated.

And snap.val() is the JSON object above. How ould I get the attack from main?

Upvotes: 1

Views: 71

Answers (1)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

In your case it would be:

obj.player["player:616320"].skills.main.attack

Where obj is the JSON object.

It's a tree where after the . is the child like so: parent.child. When there is a value that can't be represented normally you need to do parent["some-Value"].

In your case it seems that playerData is actually the value of obj.player["player:616320"] and not the entire JSON object. In that case the same concept applies:

playerData.skills.main.attack

Upvotes: 4

Related Questions