Exploring the power of AngularJS through JSON with multidimensional arrays

My goal is to construct a multidimensional array capable of storing 6 JSON responses. To seek guidance, I have consulted other resources such as this thread on multidimensional arrays in Angular.

However, upon testing my console log for the multidimensional array, I am met with the output "Stat array: undefined". Simply calling an index of the entire 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);
                }
            );
    }

The initial 5 arrays contain the direct responses and function as intended – verified through console logs and HTML view utilization.

At present, the final console log displays "Stat array: undefined". I ponder if there's an alternate method to structure my responses within the multidimensional array; for instance, attempting to access speed using [6][0] prompts an error.

If anyone could shed light on whether it's the array setup or JSON processing that's inducing this issue, I would greatly appreciate the insight. Thank you.

Answer №1

To properly structure your data, make sure to create an object instead of an array like this:

$scope.pokeObject = {
    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
};

Answer №2

angular.module('app',[]).controller('ctrl',function($scope,$http){
$scope.pokeArray = new Array(11);
        $http.get("http://pokeapi.co/api/v2/pokemon/charmander.json")
            .success(function (response)
                {
                    //Extracting data from API response
                    $scope.pokeArray[0]  = response.forms[0].name;
                    $scope.pokeArray[1]  = response.id;
                    $scope.pokeArray[2]  = response.height;
                    $scope.pokeArray[3]  = response.sprites.front_default;
                    $scope.pokeArray[4]  = response.sprites.front_shiny;

                    //Assigning stats to array elements
                    $scope.pokeArray[5]  =  response.stats[1].base_stat;
                    $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
                        }];

                    //Logging data to console
                    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][0].speed);
                });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
{{pokeArray[6][0].speed}}

</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connect an input in VueJS to a VueX store state value

As someone new to VueJS, I'm currently working on a VueJS application that provides information about a Github user. For example, you can check out details for . I've set up a store using VueX, but I'm facing an issue with updating the valu ...

Using Python to extract parameters from a JSON object in a request

Trying to pass a JSON in the request data body, here is an example: curl --data "data={"applist":{"ads":{"ad":[{"adsid":1,"view_points":25,"view_type":"full","comment":"Success"}]}}}" POSTURL When attempting to load the JSON, it results in an error:- da ...

Load a Javascript file from the local server

My website is encountering a problem when trying to load a script from a localhost server. The error message displayed is PROTOCOL ERROR: https://localhost:4200/script/test.js net::ERR_SSL_PROTOCOL_ERROR Here is the code snippet causing the issue: <!DO ...

Purge IndexedDB data on tab closure

Storing data in indexedDB instead of sessionStorage is necessary due to the size exceeding 5 MB. I'm uncertain about the cleanup strategy. I want the data to persist during page reloads or navigation, but I'd like it removed if the user closes t ...

Steps to avoid reinitializing the component upon changing routes in an Angular 9 component

In my component, the width of a chart is stored in a variable (because I can't use style for d3). However, every time the route changes, all variables in this class component become undefined. I have tried using ngIf, services (which also become unde ...

Seeking further clarification on the topic of `custom Directive` in AngularJS

Implementing a login form in my application, I have chosen to display errors on blur of the input element. Although this approach works, I have encountered several questions regarding a custom directive I created without thorough explanation from the tuto ...

Unable to successfully remove item by ID from mongoDB within a Next.js application

Currently, I am developing an application using NextJS for practice purposes. I'm facing challenges in deleting single data from the database with the findByIdAndDelete function. Error encountered: CastError: Cast to ObjectId failed for value "undef ...

Switching up the default font style within TinyMCE

After successfully changing the default font within the editor using the guidelines provided here, I have encountered a new issue. The original default font no longer appears in the font drop-down list. The previous default font was Verdana, and the new d ...

Creating a cookie on click event to change the background

I am working on changing the background of a div onclick and storing it with a cookie. However, I am facing some issues with my code. I can't determine if the cookie has been properly set, and I am unsure about changing the background with the value o ...

What could be the reason for my ng-init not functioning properly?

<body ng-init="user=${userID};month=${month};curPageNum=${currentPage}"> Using JSP, I set initial values in the body tag. However, in the controller, I have the following code: console.debug($scope.user + " "+$scope.month} The issue is that only ...

Exploring a Multidimensional Array with Nested Loops

I have a complex array structure that I want to transform into an HTML form. However, I am struggling with looping through the nested arrays to retrieve and display the values I need for the form elements. Does anyone have any suggestions or solutions on ...

Error Encountered: Eclipse Luna Crashing due to Null Pointer

Every time I click on a project, JSP page, or Java file in my Eclipse Luna, it keeps throwing a 'Null Pointer Exception'. This problem started happening after I attempted to install an AngularJS plugin. I am confused and not sure what the issue i ...

Instructions for utilizing img.shape() in Javascript

import cv2 open image file img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED) fetch image dimensions dimensions = img.shape image details height = img.shape[0] width = img.shape[1] channels = img.shape[2] print('Image Dimensi ...

The Angular pattern is functioning properly on Plunker, but it is not working when trying

Can someone help me understand this confusing issue? I have the same code in Plunker and locally, but it only works in Plunker. Why is that happening, especially with ng-pattern or HTML5 pattern? In the first image on my local server, I entered "011.11". ...

What could be causing my browser to display "uncaught referenceerror" in this situation?

Just running some browser tests to troubleshoot - everything's smooth sailing until this line is reached: responseJson = JSON.parse(localReq.responseText); So, when I evaluate JSON.parse(localReq.responseText), the correct value comes through. But a ...

What is the method of using "*" as the value for allowedModules in a jsreport configuration file to enable all modules?

I am having an issue when trying to generate a report using jsreport STUDIO. The error message I received is as follows: An error occurred - Error during rendering report: Unsupported module in scripts: request. To enable require on a particular module, ...

javascript The unchecking of a checkbox is not functioning

I am facing an issue with this JavaScript code. The problem is that when I uncheck a value, it removes all the values from the result instead of removing just the specific unchecked value. Can someone please help me with this? <script> window.addE ...

Adding Information to Mongodb with C#

using MongoDB.Bson; using MongoDB.Driver; protected static IMongoClient client; protected static IMongoDatabase db; public async void Insert() { client = new MongoClient(); db = client.GetDatabase("Database"); str ...

Tips for efficiently showcasing array responses in Vue.js and Laravel

I am looking to showcase array data within a .vue file, but I am uncertain about the process. This is my attempt: <template> <div id="app"> <table class="table table-striped"> <thead> <tr> ...

Display a modal popup form in ReactJS when a particular key is pressed

As a beginner in ReactJS, I am currently developing the frontend of a web application that requires multiple modal dialogues to be displayed based on specific key combinations. To achieve this functionality, I plan to utilize JQuery-UI for the modal dialog ...