Typescript/Angular array manipulate objects on copy

244 views Asked by At

I am trying to filter an array by an HTML input and encounter some problems:

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

The filtering works great, but when I remove a character, the search result is not adapted accordingly. It seems that the copyJson gets modified too, when I print the one, it contains the same objects as the json, which was filtered before.
I think this is some problem with references, can someone help me?

2

There are 2 answers

0
Danyal Imran On BEST ANSWER

The problem is that you are copying the reference, and therefore modifying the source object as well (this.copyJson), when this.json changes.

fix:

this.json = {...this.copyJson};
0
adz5A On

This is because you are doing a shallow copy of the this.json and your are filtering a nested object json.pools.

You need to make a deep copy of this, see lodash.cloneDeep : https://lodash.com/docs/4.17.10#cloneDeep