1

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?

3
  • Well if data is the whole object then data.username won't work - you'd need data.player["player:616320"].username Commented Jul 25, 2015 at 21:43
  • If data.username gives you test1, then data is probably player:616320 in the tree. To get the value of attack I would think you can use data.skills.main.attack. Commented Jul 25, 2015 at 21:45
  • If data.username works then the rest is of the same format. As in data.skills.main.attack to get the value 1. Basically just add . and whatever keys you want or you want to go into. Commented Jul 25, 2015 at 21:46

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

parent["some-value"] would have been a better example :)
I got it using this based off your answer: playerData.skills['main']['attack']
@DanF Great! You actually can just do main.attack other than ['main']['attack'], but either way will work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.