arrays - 如何在Angular 6中使用JSON.stringify(object)将对象转换为字符串后将值推送到数组中
问题描述
我已经声明了一个数组,因为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);
});
}
我得到的错误是 => ERROR: Argument of type string is not assignable to parameter of type answers in 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
因此,每当我尝试更新数组的值时,它都会在 0(零)索引中更新this.answers
。
let indexValue = this.answers.findIndex(obj => obj.question == data.question);
console.log("Index Value =>" + indexValue);
this.answers[indexValue] = data;
但是,我将索引值设为 -1(有时)。有人可以建议我如何将值存储在数组中,以便我可以在根据问题(模型类)找到索引后更新这些值。
解决方案
不要使用JSON.stringify()
函数将对象转换为字符串。
只是改变
JSON.stringify(data);
至
data;
到处。
推荐阅读
- sql - 无重复的 Oracle SQL 语句
- python - 从 Pandas 数据框中访问列表中的值
- c++ - 如何将 2D 多边形三角剖分算法移植到 3D?
- jquery - 在 $(document).ready(function() 中时,console.log 不起作用
- angular - 在 Angular 6 组件 ngOnInit 函数中测试 rxjs 间隔
- postfix-mta - Postfix 问题 通过 telnet 拒绝中继访问
- python - 拟合回归模型导致 sklearn 中的“ValueError:‘列名’不在列表中”
- c# - 无法在 IE 上使用 Selenium Webdriver 粘贴到输入字段中
- r - R 今天()中的错误:找不到函数“今天”
- php - 我想显示来自 api 的所有结果