-1

I am working on a project where I am using Angular 5. I am a newbie to angular so I am stucking while getting values from json object. Here is 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}}]

All I need to access unit_1 values. I am using a table to show this data so I want to iterate td. I am getting other data very easily by using *ngFor. Please provide me an easy solution to extract data from unit_1 key. It would be great if I can manage all this in html view instead of typescript.

Neeraj
  • 652
  • 10
  • 18
  • If you can change your JSON response, change it to something like this [{"student_guid":"198", "seconds":510, "session_count":0, "unit_1":[0,0,0,0,0,0,0,0]}]. Suggesting this response because I can see your unit_1 value is object with keys are just a incremental value starting from 0. Once you change it to provided response you can itrate with*ngFor – jaybutani Apr 03 '18 at 10:03
  • Hi sir. Thanks for reply. I can't change response because someone else working on server end. I just want to iterate over these values and want to display them in view using table – Neeraj Apr 03 '18 at 10:10
  • Hi Neeraj. I see you are quite new to Stackoverflow. Welcome! In order for us to be able to see what is wrong with your concrete code, you will actually need to show us some of it. I will suggest that you try to submit a minimal complete example that reproduces your problem: https://stackoverflow.com/help/mcve – Sámal Rasmussen Apr 03 '18 at 11:21

2 Answers2

1

Here is the solution of my issue.

  1. 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. Import it to your component

  3. Use it as follow to get values from object
<li *ngFor="let unit of student.unit_1 | valueArray">
{{student.unit_1[unit]}}</li>
  1. You can also access keys if you want, here is the example
<li *ngFor="let unit of student.unit_1 | valueArray">{{unit}}</li>
Neeraj
  • 652
  • 10
  • 18
0

You are trying to iterate over a object and that's why you will not get it with the standard *ngFor. I found a while ago a post here where they create a pipe to iterate a object using *ngFor.

Anyway, I recommend you recheck your data structure as an array would fit you better and it will ease your development. Check the docs for more info on *ngFor

AntonioGarcía
  • 1,140
  • 2
  • 15
  • 25