按值复制数组在 Angular 的 foreach 中不起作用

问题描述 投票:0回答:2

我正在尝试复制数组元素中的数组并根据我的需要进行操作。

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

我每次都使用

[...this.question?.options]
来获取新的选项副本。但它总是保存每个元素中数组的最后一个值

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

javascript arrays angular typescript deep-copy
2个回答
0
投票

我确实看到每个标签元素下填充了正确的选项数组。只需使用 html 中的 pre 标签格式化 json 即可获得更好的视图。

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


0
投票

我希望这可以帮助你:

扩展运算符([...this.question?.options])正在创建选项数组的浅表副本。由于浅拷贝中的对象与原始 options 数组中的对象是相同的对象,因此修改浅拷贝中的 e.checked 也会影响原始数组中相应的对象。尝试按以下方式使用深复制:

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;
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.