1

I am trying to copy array in element of array and manipulate as per my need.

 this.question?.labels.forEach((element) => {
      element["options"] = [...this.question?.options]; // I've tried json.stringify() as well but not worked
      element["options"].forEach(e => {
        e.checked = this.question?.userAnswers.find(i => e.key === i.value && element.key === i.key) ? true : false;
      });
    });

I've used [...this.question?.options] to get new copy of option every time. but it always saved last value of array in each element

https://stackblitz.com/edit/pass-array-by-value?file=src%2Fapp%2Fapp.component.ts

enter image description here

Ubiquitous Developers
  • 3,637
  • 6
  • 33
  • 78
  • Does this answer your question? [Deep copying objects in Angular](https://stackoverflow.com/questions/36124363/deep-copying-objects-in-angular) – Boaz Mar 02 '21 at 13:17
  • The spread operator `...` would only make a _shallow_ copy of the array. The array elements which are objects would still maintain their reference and will be mutated. You will need a _deep_ copy. See the duplicate linked. – Boaz Mar 02 '21 at 13:19
  • I've tried JSON.parse(JSON.stringify(Object)) as well, but it is not working. I've created stackblitz link for your reference and if you want to check – Ubiquitous Developers Mar 02 '21 at 13:30

1 Answers1

0

I do see the right options array populated under each label element. Just formatted the json using pre tag in html to get a better view.

Stackblitz - https://stackblitz.com/edit/pass-array-by-value-b1f6aq?file=src/app/app.component.ts

Zam Abdul Vahid
  • 2,389
  • 3
  • 18
  • 25