Locating a specific entry in a custom object array based on a property

Currently working on an Angular 2 app using Typescript and encountering a challenge. There is a service that retrieves an array of questions structured 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']),

There is a button that enables users to modify the question (including the id). The updateQuestion function appears as follows:

updateQuestion(questionId: number, newQuestion: Question) {
   //Find question in array
   //Delete this entry
   //Add new question to array

}

The main struggle lies in the initial task: locating a question within an array. Attempts have been made using

this.questions.find(question => questionId == id) 

however, 'id' is undefined at that point and accomplishing it remains uncertain.

The core issue revolves around pinpointing the correct entry in the questions array where id equals questionId

Any guidance provided will be highly appreciated!!

Answer №1

After some investigation, I discovered that the issue lied within the Question model. To address this, I made adjustments to my Question model as shown below:

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;
}
}

Subsequently, I updated my service implementation:

updateQuestion(questionId: number, newQuestion: Question) {
    const questionIndex = this.questions.findIndex(x => x._id == questionId);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting a buffer to a string in Python 3, similar to Node.js 6.0.0

I am currently in the process of translating an old node.js library into Python and I am facing difficulties trying to replicate the behavior of Buffer.toString() in Python. The library is used in a node 6.0.0 environment. While researching, I came acros ...

Don't forget the last click you made

Looking for a way to style a link differently after it has been clicked and the user navigates away from the page? Check out this code snippet I've been using: $(document).ready(function(){ var url = document.URL; function contains(search, find) { ...

Transforming an SQL Query into JSON format using Oracle 11g in Oracle Application Express (APEX)

In my Oracle APEX v4.2 project, I am dealing with a sizable table containing about 40 columns and up to 50 rows. My goal is to use SQL to fetch the data from this table and convert each row into a JSON object. Operating on Oracle 11gR2, I require this JSO ...

Retrieving the Selector Value during a Change Event

Is there a way to retrieve the selector value in a change event? I attempted this approach: $("#frek_menonton_tv :input").change(function(){ $(this).selector; }); However, it only returns an empty string. Desired outcome: frek_menonton ...

Using *ngIf in Angular to display a list of items only when the length is greater than 0

<h1>{{title}}</h1> <ul> <li *ngFor="let breed of data.message | keyvalue"> <a [routerLink]="['/picsofbreed']" [queryParams]="{breed: breed.key}" target="_blank">{{breed.k ...

What could be the reason my ImageMapster jquery plugin is not functioning in the Power Apps portal's code editor?

I'm attempting to add hover effects to an image map within my Power Apps portal site using the code editor. However, when I include the script: <script type="text/javascript">$('img').mapster();</script> for the desire ...

List component in Angular not refreshing after sorting the array in the service

Currently, I am delving into the realm of Angular (version 5+) to enhance my skills by working on a small project. The project involves setting up basic routing functionalities to showcase the ContactList component upon selecting a navigation tab. Addition ...

Launch a Bootstrap modal window using Spring MVC backend

I am working with a Spring MVC controller and a bootstrap page. My goal is to display a confirmation window when submitting a form and sending some payload to a specific endpoint if certain conditions are not met: API: @PostMapping(value = "/pairs") ...

Retrieving the inner content of several paragraph elements, all consolidated into a single string

I'm trying to extract the inner HTML of multiple paragraph elements from a string and I need some help. Here's an example input: let HTML = "<p class="Paragraph" >Hello, World 1!</p><p class="Paragraph" >Hell ...

What is the secret to planning an event that spans a significant period of time?

Let's say there's this div in the code: <div [hidden]="!isNotificationDisplayed" class="notification"> <h2 align="center" class="set-margin" #notification>Node was...!</h2> <h4 alig ...

How to automatically set focus in a text box when a Kendo Window is opened

I am working on a project where I need to set the focus on the first field of a kendo-window when it opens after clicking on a button. I used ViewChild to declare the field, but it is showing as undefined when the window is opened because it hasn't be ...

Resetting the internal state in Material UI React Autocomplete: A step-by-step guide

My objective is to refresh the internal state of Autocomplete, a component in Material-UI. My custom component gets rendered N number of times in each cycle. {branches.map((branch, index) => { return ( <BranchSetting key={ind ...

Is it possible for JavaScript to interact with elements that are created dynamically?

It's puzzling why the newly generated elements remain unseen by the next function that is called. Any insights on how to address this issue would be greatly appreciated! Resolve: Incorporate async: false to deactivate the asynchronous feature in order ...

Error: Angular 6 resolve consistently returns undefined

Seeking to implement my service for retrieving values from the database server and displaying them onscreen, I have set up a resolver for the service since the database can be slow at times. However, no matter what I try, the data received through this.ro ...

Using Vue for Firestore pagination

Utilizing the bootstrap-vue pagination component: <b-pagination v-model="currentPage" :total-rows="rows" :per-page="perPage" ></b-pagination> Component.vue: export default class PaginatedLinks extends Vue { public currentPage: number ...

The Mean stack application is throwing an error message: "user.comparePassword is not

This section contains my user models in the file named "user.js". var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); let emailLengthChecker = (email) => { if (!email) { return false; } else { if (emai ...

Adding a new row with a maximum number of columns in the material table

My table creation process involves adding an extra row with a progress bar after each existing row, similar to this: https://i.sstatic.net/yVsmp.png The second tr in my setup has a colspan="8" I want to achieve the same layout as the material ...

What are the reasons for the slower runtime of node.js compared to the Google Chrome console

It's interesting to note that both Chrome and node.js operate on the same V8 javascript engine. Here is my take on it: Chrome, despite running internal executions, also handles additional UI tasks which could potentially slow it down On the other ha ...

The function res.send is undefined in this context

I am struggling to send the data back to my JavaScript file after making an API call. I attempted to use res.send but encountered an error. I can't seem to figure out how to return the information back to the frontend JavaScript file. (I removed my ke ...

React-router Link failing to load content

In my current development setup, I am utilizing React and Rails with AWS S3 to create a platform similar to YouTube. I've encountered an issue with navigating to different video content within a watch page using react-router. When clicking on a link t ...