首页 > 解决方案 > 在数组上使用地图函数 - 如何仅转换一个字段(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
      });
  }

标签: angular

解决方案


使用 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
      });
  }

推荐阅读