1

I'm new with Javascript and bumped into a funny problem. I have a Json which is alike the following:

{ 
"TEAM-8f382740": {[ 
  {info1},
  {info2},
  {info3}
]}
}

I'm trying to get the content behind that "TEAM-8f382740" in my code:

$http.get('https://eune.api.pvp.net/api/lol/eune/v2.4/team/TEAM-8f580740')
   .success(function(data) {
      $scope.champs = data.??; //what to put here to get just {info1},{info2}...
});

Problem is the 'TEAM-8f382740' is a variable and the same time in a tricky form. I tried the following:

$scope.teamName = 'TEAM-8f580740'; //or var teamName='TEAM-8f580740';
$http.get('https://eune.api.pvp.net/api/lol/eune/v2.4/team/TEAM-8f580740')
 .success(function(data) {
    $scope.champs = data.$scope.teamName; //data.teamName doesn't work either
});

So how to get that [{info1},{info2},{info3}] content from the Json? I tried with other kind of Jsons and seems if instead of "TEAM-8f580740" there is for example the word "champions" that is not changing, then I can just get the content behind it by $scope.champions = data.champions;

1
  • 2
    data["TEAM-8f382740"] should work Commented Oct 15, 2014 at 18:22

1 Answer 1

2

You were close:

$scope.teamName = 'TEAM-8f580740'; //or var teamName='TEAM-8f580740';
$http.get('https://eune.api.pvp.net/api/lol/eune/v2.4/team/TEAM-8f580740')
 .success(function(data) {
    $scope.champs = data[$scope.teamName];
});

If you want to get a value from a Javascript object, there are two options: using dot notation or bracket notation. Say you have this object:

var foo = {
    "key": {"another_key": "baz"}
}

You can get the value using the dot notation:

foo.key
#returns {"another_key": "baz"}

If you don't know they name of the key until runtime, you can't use the dot, so you can use bracket notation to accomplish the same thing.

var key = "key"
foo[key]
Sign up to request clarification or add additional context in comments.

2 Comments

Great! Thanks :) Works now. I knew the solution is simple but just couldn't find it anywhere.
Great job of explaining dot vs. bracket notation in addition to answering the question. So in addition to knowing what works for the original use case the OP should now understand how to solve future use cases where he needs to access property via variable.

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.