Tecwyn Tecwyn - 7 months ago 92
Javascript Question

AngularJS multidimensional arrays with JSON Data

I am attempting to create a multidimensional arrays that will hold 6 JSON responses. I have been looking at others for help: multidimensional array in angular

but when I test my console log for the multidimensional array I get the output "Stat array: undefined", calling just this index of the whole array returns [object Object].

$scope.pokeArray = new Array(11);
$http.get("http://pokeapi.co/api/v2/pokemon/"+searchedName +".json")
.success(function (response)
{
//Get first form FORMS array, assign name
$scope.pokeArray[0] = response.forms[0].name;
//13 ID
$scope.pokeArray[1] = response.id;
//10 Height
$scope.pokeArray[2] = response.height;
//7 Sprites
$scope.pokeArray[3] = response.sprites.front_default;
$scope.pokeArray[4] = response.sprites.front_shiny;
//3 Stats 5-11
//Speed
$scope.pokeArray[5] = response.stats[1].base_stat;

//Index 6 = Array of 6
$scope.pokeArray[6] = [
{
speed : response.stats[0].base_stat,
spDefense: response.stats[1].base_stat,
spAttack : response.stats[2].base_stat,
defense : response.stats[3].base_stat,
attack : response.stats[4].base_stat,
hp : response.stats[5].base_stat
}];

console.log("Name: " + response.forms[0].name);
console.log("Height: "+ response.height);
console.log("ID: " + response.id);
console.log("Array: " + $scope.pokeArray);
console.log("speed: " + response.stats[1].base_stat);
console.log("Stat array: " + $scope.pokeArray[6].speed);
}
);
}


As you can see, my first 5 arrays are all containing the direct responses and this works fine, I have tested it with my console logs and I have used the information in my html view.

Currently, the last console log returns "Stat array: undefined". Maybe, theres a different way I should be doing my responses in the mutlidemensional array but I'm not sure, I thought maybe if i tried to use [6][0] to get speed that could work? But this causes an error.

If anyone could tell me if it is my array, or JSON handling that is causing an issues, that would really help me out. Thank you.

Answer

You're creating an array instead of creating an object, do this:

$scope.pokeArray[6] = {
                        speed    : response.stats[0].base_stat,
                        spDefense: response.stats[1].base_stat,
                        spAttack : response.stats[2].base_stat,
                        defense  : response.stats[3].base_stat,
                        attack   : response.stats[4].base_stat,
                        hp       : response.stats[5].base_stat
                    };