Retrieve an array of object values using Angular and TypeScript

I'm attempting to extract the values of objects in an array using a nested for loop. I am receiving JSON data as shown below and have written the following TypeScript code to achieve this. However, I am unable to successfully bind the values to the template. Please see my code below:

Here is the TypeScript code snippet:

let totalData = results['data'];
     for (var i=0; i<totalData.length; i++)
        for (var task in totalData[i]) {
            console.log("Task: "+task);
            console.log("totalTests: "+task['totalTestCompleted']);
            console.log("totalOpenIssues: "+totalData[i][task].totalOpenIssues);
        }

The JSON data received from the REST API is as follows:

   [ 
    // JSON data snippet here
    ]

I am aiming to access the keys and values of the task object as shown below:

task.totalTests
task.totalOpenIssues

When attempting to extract the JSON array object values, I encounter the following error:

ERROR TypeError: Cannot read property 'totalTestCompleted' of null

I have tried to bind these values to the template but I am facing difficulties in extracting the array of JSON object values. Can someone provide guidance on this matter?

Thank you.

Answer №1

Ensure that all elements contain the necessary task information by checking for it.

for (var key in totalData) {
  console.log('Task id: ' + key);
  // Make sure not to miss out on any important details
  if (totalData[key].task) {
        console.log('Total tests: ' + totalData[key].task.totalTests);
    console.log('Total open issues: ' + totalData[key].task.totalOpenIssues);
  }
  else {
    console.log('No task');
  }
}

Additionally, keep in mind that using for (var task in totalData[i]) will iterate through all keys of the object:

var o = { a: 1, b: 2 };
for (var k in o) {
  console.log('Key: ' + k);
}

// The above will log
Key: a
Key: b

Previously, you were accessing all keys in the following manner:

id
createdDate
inactive
job
and so on...

Answer №2

Your code has a few issues that need to be addressed. Based on the information provided, it seems that nested loops are not necessary. Additionally, there appears to be no reference to the totalTestCompleted key in your data.

let totalData = results['data'];
for (var i=0; i<totalData.length; i++) {
    // totalTestCompleted is missing: console.log("totalTests: "+task.totalTestCompleted);
    console.log("totalOpenIssues: "+ totalData[i].task.totalOpenIssues);
}

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

Issue encountered when exporting with node and mongoose

After creating some schema and exporting the model, here is the code: var mongoose = require('mongoose'); var specSchema = new mongoose.Schema({ name: String, description:String }); var qualSchema = new mongoose.Schema({ name: Str ...

Mapping a bar chart on a global scale

Are there any methods available to create bar charts on a world map? The world map could be depicted in a 3D view resembling a Globe or in a 2D format. It should also have the capability to zoom in at street level. Does anyone have suggestions or examples ...

Using Swift 5 to Generate a Dictionary from an Array

I am tasked with creating a custom dictionary from an array, specifically assigning a custom type to the first index of the array. Here is a sample array: ["ABC","ZYZ","123"] The expected result should be: [{"name" : "ABC", "type:"A"},{"name" : "ZYZ", "t ...

Determine the value of an array element based on a specified

I am in the process of creating an array, currently consisting of a single object that is computed based on other objects from a JSON file. Sampling my code // Retrieve JSON data and convert it to an object let myFile = '{"foo": {"bar": "baz"}, "thu ...

TinyMCE version 5.x - Stand out with a specific selection in a personalized drop-down navigation bar

In my customized TinyMCE 5.x dropdown menu, there are 3 options that adjust the width of the editor. I am looking for a way to indicate the currently selected option, but I am unable to interact with the menu items once they are initialized. It seems like ...

Tips for implementing lazy loading of modals in Angular 7's module structure

In a previous project, our team utilized a single "app module" that imported all necessary components, pipes, directives, and pages at the beginning of the application. However, this structure was not ideal as the app became slower with its growth. Upon t ...

Why does my Observable remain perpetually unfulfilled?

I recently started learning javascript and came across the Angular 2 Documentation where I discovered that Promises can be replaced with Observables. While experimenting with a simple code, I noticed that in addition to the expected result, I am also getti ...

Linking several asynchronous functions together in JavaScript

class Calculation { constructor(num) { this.num = num; } performAddition() { // code } performSubtraction() { // code } performMultiplication() { // code } performDivision() { // code } } const getResult = async ...

The absence of CORS headers detected in XMLHttpRequest

I am currently trying to execute an ajax call to a remote server, only for developmental purposes. I have configured CORS on my server, which is why when I request the resource through the browser, it shows that the CORS headers are present. https://i.sta ...

Creating an HTML design with divs: a trio of pictures that adjusts in size to match the viewport (sl

As a newcomer to HTML and CSS, I find myself nearing completion of my website, with the final obstacle being an image slider in the background. The Challenge: The images are not perfectly centered within the viewport. Specifically, the first image needs ...

How can I use ngx-editor to insert an HTML block at the current cursor position by clicking a button?

I am currently using ngx-editor within Angular 7. My goal is to insert HTML at the cursor's position upon clicking on parameters from a list. The current view displays how the parameter is appended when clicked, as shown in the image attached https:// ...

Tips for maintaining space beneath an image when text wraps around it

.blogimgarea { width: 38%; padding-right: 26px; float:left; } img{max-width:100%} .blogtextarea { width:55%; padding:22px 32px 0 0; float:right; } <div class="newpostregion pt70"> <div class="blogimgarea"> <img class="featblogimg" src="https ...

What could be causing my for loop to become unresponsive?

My for loop seems to be populating all fields with the last object parsed. http://codepen.io/anon/pen/EKxNaN This is my current code. I created something similar on CodePen since I can't access JSON from the original source there. var championMaste ...

Retrieve information following an Ajax call inside a pre-designed template

Upon rendering a page with data put together by EJS, the goal is to refresh a section (thirdRow) of the page whenever the user submits new data. The refreshed section should display both the newly submitted data and the existing data. Although I have obtai ...

After removing an item from the array, React fails to display the updated render

As a newcomer, I am struggling with a particular issue. I have implemented a delete button for each item in a list. When the button is clicked, the object in the firstItems array is successfully deleted (as confirmed by logging the array to the console), b ...

Is there a way to automatically redirect the main html page to a different html page upon logging in?

I have created a main page in HTML with a login box that displays a message saying "Login successful" or "Login failed" based on whether the password entered is 8 characters or more. The validation function for this works correctly, but after successfully ...

Using jQuery to populate an array with selected table items

Issue Description: I am working on an HTML page with two add buttons and two tables. Currently, when the add button is clicked, rows are appended to their respective tables. However, in the backend, I need to gather all row elements when a specific "button ...

Why is it necessary for me to utilize JSONP?

What is the significance of using JSONP? A few days ago, I inquired about not receiving a response from a rest server while using jQuery. It turns out that I need to utilize JSONP. I tested this on my own server and it was successful. Now, I am tasked wi ...

Identifying Whether Angular ng-repeat is Displaying Output or Not

I am trying to display a "No result" message when the search field does not have any matches. The current filter is working fine, but it does not show the message when there are no results. How can I achieve this? <div class="portfolio-list-wrap" ng-co ...

Downsides of utilizing variables as global entities in React components

I am currently working on integrating API data into my React component: const request = new XMLHttpRequest() let outputArray = [] request.open('GET', 'http://localhost:3005/products/157963', true) request.onload = function() { let d ...