angular - 在数组上使用地图函数 - 如何仅转换一个字段(MEAN App)
问题描述
下面是 Angular 应用的 clientsService 的 getClients() 方法的代码片段。这是关于将从 MongoDB 接收到的数据的集合数组的 _id 字段转换为仅 id 字段 - 在 Angular 模型中使用。
请参考最里面的返回语句,在其中我通过仅使用 id 字段更改响应对象的 _id 字段来转换客户端数组 - 以匹配 Angular 客户端模型。有没有办法在不重写不改变的字段的情况下编写此映射语句。
getClients() {
this.http.get<{message: string, clients: any}>('http://localhost:3000/api/clients')
.pipe(map((clientData) => {
return clientData.clients.map(client => {
return {
// is there a better way of writing the below part. I just need to transform only one field.
id: client._id,
compName: client.compName,
title: client.title,
fName: client.fName,
lName: client.lName,
addr1: client.addr1,
addr2: client.addr2,
city: client.city,
state: client.state,
pincode: client.pincode
};
});
}))
.subscribe(mappedClients => {
this.clients = mappedClients;
this.clientsUpdated.next([...this.clients]);
// emitting a copy of clients array and not the original array
});
}
解决方案
使用 javascript 扩展运算符,您可以进行如下修改。
getClients() {
this.http.get<{ message: string, clients: any }>('http://localhost:3000/api/clients')
.pipe(map((clientData) => {
return clientData.clients.map(client => {
const object = { ...client };
object.id = client._id;
delete object._id;
return object;
});
}))
.subscribe(mappedClients => {
this.clients = mappedClients;
this.clientsUpdated.next([...this.clients]);
// emitting a copy of clients array and not the original array
});
}
推荐阅读
- c++ - 有效地将参数传递给 CUDA 内核
- node.js - 本地主机拒绝连接我的第一个 React 项目
- android - 如何在 Delphi 11 的 Androidapi.JNI.Support 中使用新的接口函数名称?
- ios - iOS Swift WebSocket - 为 Vapor 服务器设置会话数据
- c++ - 不被识别为支持的文件格式 ECW gdal api
- python - Python验证类属性
- mysql - Mysql交叉表固定列查询不显示某些多语言字符
- reactjs - 从 github 移动存储库,并获得 3 SyntaxErrors `Unexpected token`
- html - 如何使用owl-date-module将纪元时间发送到Angular中的后端API?
- c# - How to avoid duplicates when inserting data using OleDB and Entity Framework?