[英]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.cloneDeep
: https : lodash.cloneDeep
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.