angular - 将对象列表从响应转换为不同的对象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"
}
解决方案
鉴于它是一个数组,您还需要使用数组的map
函数。这将确保数组中的每个项目都被转换。
您可以执行以下操作:
this.getData()
.pipe(
map(res => res.map(item => ({id: item.setId, type: item.name})))
).subscribe(res => console.info(res));
推荐阅读
- php - PHP嵌套函数逻辑错误-用WPML翻译functions.php
- typescript - 在 Jest 中,如何仅在特定测试中模拟外部模块?
- c# - Azure API 应用程序连接到本地文件共享
- python - 将 VBA 代码转换为 python 代码以便于集成
- ruby - 如何使用自定义按钮从 Cloudforms 中的 VM 中删除磁盘?
- ruby-on-rails - NameError - 未初始化的常量 ContactController
- swift - Swift 5 转换后允许任意负载不起作用
- c# - 我不太确定 math.ceiling 在这里做什么
- javascript - 如何通过 Chrome 扩展内容脚本使用“playVideoById()”?
- javascript - 什么是 TypeScript 中用于读取/获取数据的 *NgFor