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

4
  • Does this answer your question? Deep copying objects in Angular Commented Mar 2, 2021 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. Commented Mar 2, 2021 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 Commented Mar 2, 2021 at 13:30
  • stackblitz.com/edit/… Commented May 8, 2024 at 15:41

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

I wish this could help you:

spread operator ([...this.question?.options]) is creating a shallow copy of the options array. Since the objects in the shallow copy are the same objects as those in the original options array, modifying e.checked in the shallow copy also affects the corresponding objects in the original array. Try using deep copy in the following way:

this.question?.labels.forEach((element) => {
    element["options"] = JSON.parse(JSON.stringify(this.question?.options)); // Deep copy of options array
    element["options"].forEach(e => {
        e.checked = this.question?.userAnswers.find(i => e.key === i.value && element.key === i.key) ? true : false;
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.