首页 > 解决方案 > 如何在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(有时)。有人可以建议我如何将值存储在数组中,以便我可以在根据问题(模型类)找到索引后更新这些值。

标签: arraysangulartypescriptarraylist

解决方案


不要使用JSON.stringify()函数将对象转换为字符串。

只是改变

JSON.stringify(data);

data;

到处。


推荐阅读