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?
4 Answers 4
Please try
if(games.waitingGames.arithemetic[gamesize].games.length == 0)
4 Comments
waitingGames is a variable name, not an object property, so you can't reference it by saying games.waitingGames -- that's why it's undefined.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.
4 Comments
., edited. Shouldn't gametype be equal to "arithmetic"?games? Does it work if you just write: games[gametype][gamesize].games.lengthYou 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){
}
}
Comments
Fixed, had to use the brackets to change use the variable content to reach where i wanted inside the JSON object, thanks all
object[variableName]. It makes sense that dot-notation wouldn't work sinceobject.variableNameimplies that there is a property of the object namedvariableName, when it should bekeyName, which is just stored in the variable.