Iterate through json string in Observable angular

2020-05-08 20:40发布

问题:

Following is my html code,

            <tr *ngFor="#c of content|async">           
                <td> {{c.name}}</td>
                <td>{{c.skill}}</td>
            </tr>

and in my json,

[{"name":"abc","skill":"xyz"}]

This is working but i need to iterate through this json string as,

var obj = {a: 1, b: 2};
for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    var val = obj[key];
    console.log(val);
  }
}

this code is in javascript I want to do this in typescript.

回答1:

You could create a custom pipe to return the list of key for each element. Something like that:

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

and use it like that:

<tr *ngFor="#c of content | async">           
  <td *ngFor="#key of c | keys">{{key}}: {{c[key]}}</td>
</tr>


标签: angular