Tips on retrieving data from a JSON object

I'm currently on a project involving Angular 5, and I'm still new to using Angular so I'm facing some challenges retrieving values from a JSON object. Here's the JSON response:

[{"student_guid":"198","seconds":510,"session_count":0,"unit_1":{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0}}]

My main objective is to access the values of unit_1. I'm displaying this data in a table and would like to iterate through the td elements. Retrieving other data with *ngFor is simple, but I need an easy solution to extract data from the unit_1 key. It would be ideal if I could handle all of this directly in the HTML view without involving typescript.

Answer №1

After tackling the issue, I've come up with a solution.

  1. To start off, create a pipe

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'valueArray',
    })
    export class ValueArrayPipe implements PipeTransform {
    
      transform(value: any, args: any[] = null): any {
            return Object.keys(value)//.map(key => value[key]);
      }
    }
    
  2. Next step is to import it into your component

  3. Now, use the following code snippet to extract values from an object
<li *ngFor="let unit of student.unit_1 | valueArray">
{{student.unit_1[unit]}}</li>
  1. If you wish to access keys as well, here's an example for that
<li *ngFor="let unit of student.unit_1 | valueArray">{{unit}}</li>

Answer №2

If you're attempting to loop through an object, the standard *ngFor won't work for you. I came across a helpful post here that discusses creating a pipe to iterate over objects using *ngFor.

That being said, it might be worth revisiting your data structure and considering if using an array would be more suitable and simplify your development process. Take a look at the documentation for more information on *ngFor

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

Converting a JSON object into a different format using TypeScript

Looking for advice on how to efficiently convert JSON data into a specific format without hardcoding any values like "root" or "Amount". I want to create a reusable function that can be used in various scenarios. Currently, I am working with TypeScript and ...

Best Practices for TypeScript and React: How to Handle Component State for Mounted Components

One technique to avoid calling .setState() on an unmounted component is by using a private property like _isMounted to keep track of it, as discussed in a blog post. I have implemented this method as follows: class Hello extends React.PureComponent{ _isM ...

Retrieve a value from a nested JSON object and assign it to a new key in the same object with

I am facing a challenge with the following input JSON: { "stores": { "1100": { "metric1": "27", "metric2": "3013775", "indicator": 8.96 }, "1200" ...

Using Froala events in Angular 2: A guide

Currently, I am incorporating Froala into my Angular 2 project. I have managed to upload an image successfully but am encountering issues triggering the image.uploaded event. The Froala document provides an example of how the event should be implemented: ...

Is the position of 'subscribe()' in the code important?

My query revolves around the positioning of code utilizing RxJS, specifically involving subscribe. If I were to place the following example inside a function: this.genericService.getXYZ().pipe( takeWhile(() => this.componentActive) ).subscribe ...

Organize the attributes of components on the following line in Visual Studio Code

Is there a method to configure the VS code formatter for Angular 2+ templates to ensure that attributes are wrapped in a new line? I prefer this formatting: <app [input1]="input1$ | async" [input2]="input2$ | async" (inputChanged)="set ...

Comparison between Django serializers and rest_framework serializers

Exploring the distinction between Django serializers and rest_framework serializers in my current web application project. I am looking to integrate the API into the main app without creating a separate module for API functionality. Which serializer should ...

Encountered an error while attempting to execute Angular application due to schema validation failure

Encountering errors in my Angular 7 Application on the development server. After running ng serve, below is the error that surfaced: D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1>ng lint -fix Your global Angular CLI ...

Is it necessary to increment the major version of a package when updating one of its dependencies to a major version?

As I explore upgrading an RxJS dependency from v5.5 to v6 in my npm package, I am not expecting any challenges based on the migration guide. However, I am contemplating whether the updated version of my package should trigger a new major release. While I ...

The subscription data for nested classes appears to be displaying as undefined

In my current project, I am utilizing Angular 8 and facing an issue with a nested class. The problem arises when trying to access data from an observable subscribe operation in the child class (Players) within the main Tournament class. Until the data is r ...

Learn how to efficiently convert JSON data into a dictionary containing strings and SoilStat objects by utilizing the FastJSON library

Can FastJSON convert JSON data into a dictionary format? The key in the string represents the name of the soil. Thank you very much! "Soil": [ { "name": "Pebbiland", "retentionrate": 1, "cost": 100 ...

The TSX file is encountering difficulty rendering an imported React Component

Upon attempting to import the Day component into the Week component (both .tsx files), an error is thrown: Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. ...

Select the data you wish to showcase on Highcharts

When it comes to loading a CSV into Highcharts with Angular, my usual approach is as follows: export class OutputGraphComponent implements OnInit { public options: any = { chart: { type: 'column' }, data: { csvURL: path.to ...

Cypress and Cucumber synergy: Experience automatic page reloads in Cypress with each test scenario in the Describe block

Hey, I'm facing an unusual issue. I have a dialog window with a data-cy attribute added to it. In my cucumber scenarios, I have one like this: Scenario: Users open dialog window When the user clicks on the open dialog button I've written Cypre ...

Customizing npm package within an Angular 13 project

Currently, I am working on an Angular application (v13.3.10) that relies on the ngx-markdown package. Unfortunately, I have encountered several bugs within this package and I am attempting to make edits locally in order to see changes reflected when runnin ...

Custom positioning of Mui Snackbar in V5

I've been attempting to position a Snackbar in the top right corner with some customization for the top property, but I'm struggling to get it to display correctly. Here's what I've tried: import React from "react"; import { ...

Guide to setting the current slide in your ngx owl carousel using Angular

Looking for a solution to dynamically set an active slide based on index within a carousel. Attempted to apply the classes "active" and "center". The newsId variable in the example below is retrieved from another page and has been verified. <owl-carouse ...

Using Vue 2 with a personalized Axios setup, integrating Vuex, and incorporating Typescript for a robust

I'm still getting the hang of Typescript, but I'm facing some challenges with it when using Vuex/Axios. Current setup includes: Vue CLI app, Vue 2, Vuex 3, Axios, Typescript At a high level, I have a custom Axios instance where I configure the ...

What is the process for transferring a function to reducers in Redux Toolkit?

In one of my files called Main.tsx, I have a function that sends a request and retrieves data: async function fetchProducts(productsPage = 1, id?: number) { const itemsPerPage = 5 let url: string if (id) { url = `https://reqres.in/api/ ...

Jackson: parsing an array of objects with varying types

Jackson: Converting Object Array to JSON and Back Causing Type Issues I have successfully converted an object array to JSON, but when I try to convert it back to an object array, some items lose their type. Specifically, objects like java.sql.Date are bei ...