Lea
Lea

Reputation: 1285

how to ngFor deeply nested json value with angular2

I'm trying to get value from deeply nested json object.

I tried using pipe and i succeeded in getting keys and values but they are not the right keys and values that I intended to get.

Could anyone please help me how to ngFor values I've written down below.

data: {
category:[
{0:{one:'test1', **two**:'test2'}},
{1:{one:'test3', **two**:'test4'}},
{2:{one:'test5', **two**:'test6'}}
]
number:[]
]
}

I want to ngFor 'two' values!

I currently have pipe

import { Pipe, PipeTransform } from '@angular/core';

`@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}

and in my component template, I have

<div *ngFor="let one of theme | keys">
  <div *ngFor = " let two of one.key | keys">
    <div *ngFor = "let three of two.key>
         <p id="thm-title">{{three.value['two']}}</p>
    </div>
  </div>
</div>

Upvotes: 1

Views: 1757

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 3099

Your Pipe works as you expect, you just need to make a few changes to your *ngFor loops

You're mixing array's and objects in your question, so I'm assuming your data is structured as below. This loop will output test2 test4 test6

data = {
    category: [
        { 0: { one: 'test1', two: 'test2' } },
        { 1: { one: 'test3', two: 'test4' } },
        { 2: { one: 'test5', two: 'test6' } }
    ]
}

html

<div *ngFor="let one of data | keys">
    <div *ngFor="let two of one.value">
        <div *ngFor="let three of two | keys">
            {{ three.value['two'] }}
        </div>
    </div>
</div>

Upvotes: 2

Related Questions