首页 > 解决方案 > 角度从列表中删除一列

问题描述

我正在尝试从列表中删除一列,在删除之前我将列表分配给另一个列表以进行备份。但在从列表中删除 colmun 后,备份列表中的该列也会被删除。

 this.commonService
  .fetchContractByDate(this.authService.loggedUser.companyId, this.startDate, this.endDate)
  .subscribe((response: any) => {
    const clientName = this.clients;

    this.contractListbyClient = response.data;
    this.allList = response.data;
    this.forexport(clientName, contractList);

    for (const contract of this.contractListbyClient) {
      for (const selected of this.selection.selected) {
        if (selected.name === 'startDate' || selected.name === 'endDate') {
          contract[selected.display] = this.commonService.getFormattedDate(contract[selected.name]);
        } else {
          contract[selected.display] = contract[selected.name];
        }
      }

      for (const item of this.columns) {
        delete contract[item.name];
      }
    }

在上面的代码中,从this.contractListbyClient中选择的列被删除,但是同样的变化也反映在 this.allList中。谁能告诉我如何保持列表副本不变

标签: angulartypes

解决方案


这是因为对于对象,变量的值是一个引用。因此,当您传递一个对象并更改其成员时,这些更改会在函数之外持续存在。这使它看起来像通过引用传递。

为了解决这个问题,我们应该正确地克隆该对象,一种简单的方法如下:

 this.contractListbyClient = response.data;
 this.allList = JSON.parse(JSON.stringify(response.data));

推荐阅读