What is the best way to extract an array value based on a key from a API response in AngularJS?

When making a rest call in AngularJS, I encountered an issue where I was able to retrieve simple key-value pairs from the response, but struggled with extracting values from arrays within the response in my AngularJS controller.

Here is a snippet of my code (comments are not included).

Rc.all('demo/example/db/').get('quues/').then(function(res)
  {
   $scope.demo={}
   $scope.demo.details={         
     value1 : res.Ksus.Type.Master.Origin.ID,        
       }

 $scope.array={}
   $scope.array.arrValue={         
     arrVal : res.Asus[0].AsuID,        
       }
   }

JSON:

{
  _id:123
  Ksus: {
       Type: {
       Master: {
         Origin: {
                  ID: "Demo"
                }
              }
            }
       },
 Asus: [{
     AsuID: "f4",
     Type: "SU",     
     }]
}

In my controller, I am able to access simple key-value pairs like ID: "Demo", but struggling to retrieve array values such as AsuID. The attempt to extract it using arrVal : res.Asus[0] results in the console showing undefined. Any assistance on how to resolve this issue would be greatly appreciated. Thank you in advance.

Answer №1

The reason for this issue is that you are trying to access the variable res outside of the get method. To resolve this, make sure to include the necessary code snippet as shown below:

Rc.all('demo/example/db/').get('quues/').then(function(res)
{
   $scope.demo={}
       $scope.demo.details={         
          value1 : res.Ksus.Type.Master.Origin.ID,        
       }
       $scope.array={}
       $scope.array.arrValue={         
          arrVal : res.Asus[0].AsuID,        
       }
    }

Answer №2

Just a heads up -

My understanding is that there might be a comma in your JSON response between _id and Ksus. Upon reviewing your JSON response more closely, I noticed that the Asus key actually falls under Type -

JSON -

{
    _id: 123,
    Ksus: {
        Type: {
            Master: {
                Origin: {ID: "Demo"}
            },
            Asus: [{
                AsuID: "f4",
                Type: "SU"
            }]
        }

Therefore, to access the value of AsuID, you will need to use - res.Ksus.Type.Asus[0].AsuID

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

Is there a way to temporarily hide content hidden with ng-hide from being displayed on the page?

Recently delving into the world of Angular, I've come across an issue where an element appears briefly on the page before disappearing. My goal is to prevent this behavior, but I am unsure how to go about it. The specific scenario involves a radio bu ...

Tackling Tcl JSON parsing: Mastering the art of array manipulation

I am working on parsing a JSON file using TCL. I'm facing some challenges with handling arrays in JSON after using json2dict for parsing. Below is the snippet of my code: package require json set jsonStr { { "photos": { "page": 1, "pages": "726" ...

Incorporating a jQuery word count and limit within PHP code: a step-by-step guide

I am encountering an issue with a textarea count code. It functions perfectly on its own but when I integrate it as shown below, it stops working without throwing any errors. I have been trying to resolve this for more than 3 days now. Any assistance would ...

Utilizing the JavaScript Array.find() method to ensure accurate arithmetic calculations within an array of objects

I have a simple commission calculation method that I need help with. I am trying to use the Array.find method to return the calculated result from the percents array. The issue arises when I input a price of 30, as it calculates based on the previous objec ...

Struggling with bringing Json data into Azure Log Analytics

My objective is to import Microsoft Flow API data into Azure Log Analytics. The plan involves having a Power Automate send a JSON containing the details of the Flows to Log Analytics. Below is a sample JSON structure: { "body": [ { ...

When you click on one item in a jQuery selector array, the action is being applied to all elements within the array

I've been working on implementing a cheat function for a minesweeper game that reveals a random non-bomb square (line 279) and its safe neighboring squares (the 8 squares around it without bombs). However, I'm encountering an issue where using $ ...

Obtaining the global coordinates of an object in Three.js

I need to adjust the position of an object that is already placed in a new location, but currently it is moving from the local position instead of global. this._scene.updateMatrixWorld(); this._scene.add(mesh); var v1 = new THREE.Vector3(); v1.setFr ...

The ultimate method for quickly sending and dismissing a JSON POST request in PHP

Currently, I'm in the midst of constructing and integrating a logging system for a PHP website project. The logging mechanism involves sending a JSON request to localhost where it is recorded. I'm curious: What's the speediest method for e ...

Using jQuery, retrieve JSON data from a different domain URL, even if the JSON data is not well-structured

Currently, I am utilizing jQuery's ajax function to access a URL from a different domain which returns JSON data. During my testing phase, I've encountered an issue where the presence of multiple '&quot' strings within the JSON valu ...

What are some methods for extracting a value from a separate webpage and saving it as a variable in my code?

I am utilizing graphite to obtain statistics and would like to display a justgage gauge for a specific variable. Graphite provides values in either JSON format: [{"target": "snmp.ssbSubstation.realEnergy.1", "datapoints": [[4511552439.0, 1417540920]]}] o ...

Highlighting neighboring components with the same marker when hovering in Slate JS: a step-by-step guide

// custom mouse over hook function useMouseOver() { const [mouseIsOver, setMouseIsOver] = useState(false); return { mouseIsOver, triggers: { onMouseEnter: () => setMouseIsOver(true), onMouseLeave: () => setMouseIsOver(false), ...

Having trouble with AngularJS ngRoute not displaying pages on ng-view?

I've been searching through various questions similar to mine, but I can't seem to find the solution here. For some reason, ng-view is not loading my pages. Am I overlooking something obvious? Here's my code in App.js: var app = angular.m ...

What is the most accurate way to obtain the current timestamp?

Currently, I am working towards my backend certificate at freecodecamp and one of the tasks involve returning a JSON response with the current time using chained middleware and handlers. Here is the code I have written: app.get("/now", (req,res,next)=>{ ...

Issue encountered with the latest version of Selenium web driver when using Firefox browser

I am currently using Selenium jar version 3.3.1 with Firefox 43.0.4 and Eclipse Mars.2 Release (4.5.2). When I execute the following code: import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selen ...

Exploring the functionality of two-way data binding in Angular - a beginner's guide

Transitioning from a different framework and switching from JavaScript to Angular & TypeScript has left me feeling confused about how to efficiently share data/values between components. ...

Why am I seeing back-end console errors that are related to my front-end?

Recently, I encountered an error message that prevents me from using 'import' in my front end code when trying to execute 'node index'. This issue never occurred before, and it only arose when I returned to this project. In my backend ...

PHP encountered an error decrypting the JSON data it received from JavaScript

After sending a JSON string from JavaScript and receiving it in PHP, I noticed that my PHP script is not interpreting it as JSON. The JavaScript code generates the following output: {"id_own":"Metztli Alonso","tick":"123456","ticket":"TID","comm":"test v ...

Vue.js version 3 presents an issue where the reactivity of a `v-model` is lost when the `data()` function is transformed into `

Exploring this simple example, we have an input and a p element that displays the input value: const App = { data() { return { message: "hello world!" }; } }; Vue.createApp(App).mount('#root'); <script src="https://un ...

Show a Google map when hovering over a link or text

I have been trying to implement a Google map display over text by following a tutorial. However, I've encountered an issue where the map is appearing in the wrong location – at the bottom of the page instead of where it should be. Upon inspecting th ...

worldpay implements the useTemplateForm callback function

My experience with implementing worldpay on my one-page Angular app (Angular 1.x) has been mostly positive. I have been using the useTemplateForm() method to generate a credit card form and retrieve a token successfully. However, I have encountered an issu ...