簡體   English   中英

Typescript/Angular 數組在復制時操作對象

[英]Typescript/Angular array manipulate objects on copy

我正在嘗試通過HTML input過濾數組並遇到一些問題:

  ngOnInit() {
    this.dtoService.setJsonResponse();
    this.getPool();
  }

  getPool() {
    this.json = this.dtoService.jsonResponse;
    this.copyJson = Object.assign([], this.json);
  }

  filterArray(): void {
    this.json = this.copyJson;
    this.json.pools = this.json.pools.filter((e) => 
    e.name.includes(this.filter));
    console.log(this.copyJson);
  }

過濾效果很好,但是當我刪除一個字符時,搜索結果不會相應地進行調整。 似乎copyJson被修改了,當我打印它時,它包含與json相同的對象,這是之前過濾的。
我認為這是參考文獻的一些問題,有人可以幫助我嗎?

問題在於,當 this.json 更改時,您正在復制引用,因此也會修改源對象 (this.copyJson)。

使固定:

this.json = {...this.copyJson};

這是因為您正在執行this.json的淺拷貝,並且您正在過濾嵌套對象json.pools

您需要對此進行深層復制,請參閱lodash.cloneDeephttps : lodash.cloneDeep

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM