首页 > 解决方案 > 将对象列表从响应转换为不同的对象Angular 6

问题描述

我正在尝试将响应列表转换为不同类型的对象。目前进行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"
   }

标签: angular

解决方案


鉴于它是一个数组,您还需要使用数组的map函数。这将确保数组中的每个项目都被转换。

您可以执行以下操作:

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

推荐阅读