Angular获取对象中项目的索引值



使用简单的httpclient:

this.getService.getAPI(this.profileUrl).subscribe(
    data => {
        this.profile = data;
    }
);

我得到一个看起来如下的JSON对象:

{
    "first_name": "John",
    "last_name": "Doe",
    "frequency": "w",
    "frequency_name": "Weekly",
    "delivery": "e",
    "delivery_name": "Evening",
    "timezone_offset": "America/Los Angeles"
}

因此,我知道{{ profile.first_name }}之类的东西会返回John作为一个值,但是在特定的实例中,我实际上需要获得密钥本身的值。我该怎么做?

您可以创建一个管道来操纵对象的键值对:

interface KeyValuePair {
  key: string;
  value: any;
}
@Pipe({
  name: 'keyValuePairs'
})
export class KeyValuePairsPipe implements PipeTransform{
   transform(value: Object): KeyValuePair[]{
     let result: KeyValuePair[] = []; 
     if(!!value && value instanceof Object){
        result = Object.entries(value).map(pair => ({ key: pair[0], value: pair[1] }))
     }
     return result;
   }
}

最新更新