Search code examples
angulartypescriptsplice

Angular 4 splice duplicating array objects


I have some code I simplified for this question.

    this.getDataRuleList.splice(this.count, 1, dataRuleData);
    console.log(this.getDataRuleList);
    this.count += 1;

getDataRuleList is returning an array of objects from a service. It is also being bound to a PrimeNg TurboTable without a problem.

    // get method to get service collection
    get getDataRuleList(): IDataRule[] {
      return this._dataRuleListService.dataRuleList;
    }

When I edit a row, I am trying to update an object in my bound array (getDataRuleList) by replacing the whole object with a new object. I'm using the splice method for this. The problem is, every object I replace becomes identical (see image for a better understanding). The value i'm sticking in the spliced value's place is different every time (dataRuleData) but all my array elements become this value. I'm assuming it has something to do with references but how can I avoid this happening?

image of issue


Solution

  • you can clone a new object

    const cloneData = Object.assign({},dataRuleData);
    this.getDataRuleList.splice(this.count, 1,cloneData);
    

    if you need to use deep clone you can check this example

    const deepCloneData = JSON.parse(JSON.stringify(obj1));