将对象列表从响应转换为不同对象Angular 6

时间:2018-06-09 06:48:08

标签: angular

我正在尝试将响应列表转换为不同类型的对象。 目前正在进行http调用,返回Observable<Object1>,我想将其转换为{id: string, type: string} (more info below)

getData(): Observable<Object1[]> {
return this.http.get<Object1[]>(this.url);
}

我以这种方式调用它:

this.getData()
.pipe(
//I understand this can transform each entry into { id: string, type: string } undefined
map(res => res)) 
    .subscribe(res => console.info(res));

对象设置:

class Object1 {
name: string;
setId: string;
date: string;
}    

如何实现这一目标的任何建议都将受到赞赏。

转换将导致以下Object2类型的对象列表:

Object2
{
id: Object1.setId,
type: Object1.name
}

JSON回复

{  
      "name":"Test1",
      "setId":"1",
      "date":"3456" 
   },
   {  
      "name":"Test2",
      "setId":"2",
      "date":"44556"
   }

1 个答案:

答案 0 :(得分:1)

看到它是一个数组,你也需要使用数组的map函数。这将确保数组中的每个项目都被转换。

您可以执行以下操作:

this.getData()
    .pipe(
        map(res => res.map(item => ({id: item.setId, type: item.name})))
    ).subscribe(res => console.info(res));