Angular获取对象中item的索引值

时间:2017-12-20 17:10:34

标签: angular typescript

使用简单的HttpClient:

myfunc

我得到一个如下所示的JSON对象:

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

所以我知道像{ "first_name": "John", "last_name": "Doe", "frequency": "w", "frequency_name": "Weekly", "delivery": "e", "delivery_name": "Evening", "timezone_offset": "America/Los Angeles" } 之类的东西会将John作为值返回,但在我正在处理的特定实例中,我实际上需要获取密钥本身的值。我该怎么做?

1 个答案:

答案 0 :(得分:0)

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

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;
   }
}