Monokilho
Monokilho

Reputation: 71

javascript JSON access

I have a JSON object that goes somewhat like this:

var waitingGames = {
    arithemetic:[
        {
            games:[]
        },

        {
            games:[]
        },

        {
            games:[]
        }
    ]

and so on for synonyms, antonyms and translation. My problem is that I can't seem to access the games array by using this:

var gametype = url_parts.query.type;
var gamesize = url_parts.query.size;
if(games.waitingGames.gametype[gamesize].games.length == 0)

I get that gametype is undefined, even though I already tried printing the variable and it has the right value (arithemetic in the above example). Any ideas how to fix this?

Upvotes: 2

Views: 85

Answers (4)

Monokilho
Monokilho

Reputation: 71

Fixed, had to use the brackets to change use the variable content to reach where i wanted inside the JSON object, thanks all

Upvotes: 0

Robin
Robin

Reputation: 7895

Use:

games.waitingGames[gametype][gamesize].games.length

Here you are using gametype as a variable like you meant to.

See this proof-of-concept JSFiddle demo.

Upvotes: 1

Aks
Aks

Reputation: 1587

You can access the value from inner games object using this expresson console.log(waitingGames.arithemetic[0].games);

Use a for loop to loop through arithemetic array.

for(var i =0, j = waitingGames.arithemetic.length; i<j; i++){
    if(waitingGames.arithemetic.games.length == 0){
    }
}

Upvotes: 0

Durgaprasad Budhwani
Durgaprasad Budhwani

Reputation: 977

Please try

if(games.waitingGames.arithemetic[gamesize].games.length == 0)

Upvotes: 2

Related Questions