【发布时间】:2019-09-14 15:08:24
【问题描述】:
每次我尝试访问深层属性(我猜测数组中的一个项目通过它的索引)时,我都会收到以下错误:
错误类型错误:无法分配给对象“[object Object]”的只读属性“value”
在我试图运行的代码下面找到,但会抛出上面的错误:
@Input() data: CivilLiabilityQuestionnaireModel;
public questions: CivilLiabilityQuestionnaireModel;
this.questions = { ...this.data };
const questionGroupIndex = 0;
const questionGroupItemIndex = 0;
this.questions
.questionGroup[questionGroupIndex]
.questionGroupItems[questionGroupItemIndex]
.answers[0]
.value = form[val];
更多可能的细节:
// This works
this.questions.id = 'hotdog';
// This doesn't work
// ERROR TypeError: Cannot assign to read only property 'id' of object '[object Object]'
this.questions.questionGroup[questionGroupIndex].id = 'hamburger';
我认为只有使用扩展运算符才能做到这一点,但这会将我的所有数组转换为对象,而我需要不惜一切代价保留我的数组。
这里是我尝试的传播解决方案:
this.questions = {
...this.questions,
questionGroup: {
...this.questions.questionGroup,
[questionGroupIndex]: {
...this.questions.questionGroup[questionGroupIndex],
questionGroupItems: {
...this.questions.questionGroup[questionGroupIndex].questionGroupItems,
[questionGroupItemIndex]: {
...this.questions.questionGroup[questionGroupIndex].questionGroupItems[questionGroupItemIndex],
answers: {
...this.questions.questionGroup[questionGroupIndex].questionGroupItems[questionGroupItemIndex].answers,
[0]: {
...this.questions.questionGroup[questionGroupIndex].questionGroupItems[questionGroupItemIndex].answers[0],
value: form[val]
}
}
}
}
}
}
};
【问题讨论】:
-
您尝试更改的属性似乎是defined 为只读的。所以我认为问题不是 嵌套,而是对象本身。
标签: javascript spread