我已将数组声明为public answers: Answers[] = [];
,这里的答案是我的课程,如下所示:
export class Answers {
question : string;
answer : string;
}
现在我将值添加到answers
中,如下所示:
public addAnswersToStack() {
AnswerEmitterService.get('answer').subscribe((data: Answers) => {
var isPresent = this.answers.some((el) => {
return el[0] === data[0];
});
console.log(isPresent);
if (isPresent == true) {
let indexValue = this.answers.findIndex(obj => obj.question == data.question);
console.log("Index Value =>" + indexValue);
this.answers[indexValue] = JSON.stringify(data);
this.uniqueAnswers = Array.from(new Set(this.answers));
} else {
this.answers.push(JSON.stringify(data));
this.uniqueAnswers = Array.from(new Set(this.answers));
}
console.log("Answers=>" + this.answers);
});
}
我遇到的错误是=>错误:this.answers.push(JSON.stringify(data));
中无法将字符串类型的参数分配给类型答案的参数。
我尝试过this.answers.push(data);
。完成此操作后,我将在数组中获取值:
Do you Have Multiple locations?,yes,How many Physical locations?,23,Corporate billing info,coporate
由于此,每当我尝试更新数组的值时,它都会在this.answers
的0(零)索引中进行更新。
let indexValue = this.answers.findIndex(obj => obj.question == data.question);
console.log("Index Value =>" + indexValue);
this.answers[indexValue] = data;
但是,有时索引值为-1。有人可以建议我如何将值存储在数组中,以便我可以根据(模型类的)问题找到索引后更新这些值。
答案 0 :(得分:0)
请勿使用JSON.stringify()
函数将对象转换为字符串。
只需更改
JSON.stringify(data);
到
data;
无处不在。