I'm developing an app in Angular 2 using Typescript and have a problem. I am having a service which fetches array of Questions looking like this
export class Question {
constructor(public id: number,
public question_text: string,
public answers: string[],
public user_answer: string = "none") // default to none, update on user input
{}
}
private questions: Question[] = [
new Question(0,
'How often did you eat a portion of vegetables??',
['Answer A','Answer B', 'Answer C', 'Answer D', 'Answer E', 'Answer F']),
new Question(1,
'How often did you eat a portion of fruit?',
['Answer A','Answer B', 'Answer C', 'Answer D', 'Answer E', 'Answer F']),
Then I am having a button which allows user to edit the Question (all the data including the id). My updateQuestion looks like this:
updateQuestion(questionId: number, newQuestion: Question) {
//Find question in array
//Delete this entry
//Add new question to array
}
I am really struggling with the very first task: find question in an array. I have tried some combinations with
this.questions.find(question => questionId == id)
but id is undefined there and I am not sure how to get to it.
Problem basically revolves around finding right entry in the questions array where id = questionId
Any help will be much appreciated!!
The Problem was with Question model. I have changed my Question model to be:
export class Question {
public _id: number;
public _question_text: string;
public _answers: string[];
public _user_answer: string;
constructor(public id: number,
public question_text: string,
public answers: string[],
public user_answer: string = "none") // default to none, update on user input
{
this._id = id;
this._question_text = question_text;
this._answers = answers;
this._user_answer = user_answer;
}
}
And then my service:
updateQuestion(questionId: number, newQuestion: Question) {
const questionIndex = this.questions.findIndex(x => x._id == questionId);