代码之家  ›  专栏  ›  技术社区  ›  Aeseir

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

  •  0
  • Aeseir  · 技术社区  · 7 年前

    我正在尝试将响应列表转换为不同类型的对象。 当前进行的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 回复  |  直到 7 年前
        1
  •  1
  •   user184994    7 年前

    因为它是一个数组,所以您还需要使用该数组的 map 功能也一样。这将确保对数组中的每个项进行转换。

    您可以执行以下操作:

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