Javascript Typescript/角度数组操作副本上的对象
我试图通过Javascript Typescript/角度数组操作副本上的对象,javascript,angular,typescript,Javascript,Angular,Typescript,我试图通过HTML输入筛选数组,但遇到了一些问题: ngOnInit() { this.dtoService.setJsonResponse(); this.getPool(); } getPool() { this.json = this.dtoService.jsonResponse; this.copyJson = Object.assign([], this.json); } filterArray(): void { th
HTML
输入筛选数组,但遇到了一些问题:
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
的浅层复制,并且正在筛选嵌套对象json.pools
您需要对此进行深度复制,请参见lodash.cloneDeep
:您还可以使用newArray=JSON.parse(JSON.strigify(yourray))进行复制;
this.json = {...this.copyJson};