Deep nested json to array in array / json renderin

2020-02-14 20:04发布

问题:

I want to list states and types of the following json with angular 2 *ngFor. The parental properties also should be rendered.

var test= {
  '192-168-0-16':{
    'ac395516-96d0-4533-8e0e-efbc68190e':{
      'state':  "none",
      'typ': "test"
    },
    'ac395516-96d0-4533-8e0e-efbc68190e':{
      'state':  "none",
      'typ':  "dummy"
    }
  },
  '222-21-12-12': {
    'ac395516-96d0-4533-8e0e-efbc68190e': {
      'state': "none",
      'typ': "none"
    }
  }

Angular 2:

<div *ngFor='#s of test'> <!-- also other properties should be visible -->
   <div *ngFor='#t of s'>
      {{t.state}} {{t.typ}}
   </div>
</div>

Of course this does not work. Is it possible without many data transforms? I am not sure how to get arrays of arrays of my json.

回答1:

You need to use array with ngFor. If you want to use objects at this level, you should consider to use a custom pipe.

See this answer for more details:

  • How to display json object using *ngFor

Based on this, I would refactor your code this way:

<div *ngFor='#s of (test | keyValues)'>
  <div *ngFor='#t of (s.value | keyValues)'>
   {{t.value.state}} {{t.value.typ}}
  </div>
</div>

with the following pipe:

@Pipe({name: 'keyValues'})
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;
  }
}