Tips for inserting values into an array after converting an object into a string with JSON.stringify(object) in Angular 6

In my code, I have defined an array like this: public answers: Answers[] = [];. The class Answers looks like this:

export class Answers {
    question: string;
    answer: string;
}

I am populating the answers array with values as shown below:

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

The error message I am encountering is => ERROR: Argument of type string is not assignable to parameter of type answers in

this.answers.push(JSON.stringify(data));
.

Instead of this.answers.push(data);, when I try this, the array values become:

Do you Have Multiple locations?,yes,How many Physical locations?,23,Corporate billing info,coporate

Due to this, whenever I attempt to update a value in the array, it gets updated at index 0 of this.answers.

let indexValue = this.answers.findIndex(obj => obj.question == data.question);
        console.log("Index Value =>" + indexValue);
        this.answers[indexValue] = data;

However, sometimes I receive an index value of -1. Can someone provide a suggestion on how to store values in an array so that I can update them based on the question (from the model class)?

Answer №1

Avoid converting your object into a string using the JSON.stringify() method.

Simply replace

JSON.stringify(data);

with

data;

in all instances.

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

How can I configure Angular to redirect to an error page whenever an error is encountered in an HTTP API request?

With over 50 HTTP APIs in my application, I'm looking for a way to automatically route to a specific page whenever an error message or issue arises with one of the APIs. Instead of manually adding routing to each service, I want to find a simpler and ...

Two separate menus for each root file in Ionic 2

In my Ionic 2 project, I have developed two root files: app.component and report-menu. In order to make the report-menu module accessible in the app.component.module.ts file, I imported it successfully. However, I am facing an issue where one menu is dis ...

Create a personalized button | CKEditor Angular 2

I am currently working on customizing the CKEditor by adding a new button using the ng2-ckeditor plugin. The CKEditor is functioning properly, but I have a specific requirement to implement a button that will insert a Rails template tag when clicked. For ...

Tips for integrating and utilizing the MSAL (Microsoft Authentication Library for JavaScript) effectively in a TypeScript-based React single page application

Issue I'm encountering difficulties importing the MSAL library into my TypeScript code. I am using the MSAL for JS library with typings in a basic TypeScript/React project created using create-react-app with react-typescript scripts. As someone who i ...

Getting the checked values from an AngularJS Material checkbox

<md-checkbox ng-repeat="program in ctrl.programs" ng-model="ctrl.programsSelected[program.id]"> {{program.name}} </md-checkbox> Checked Items: {{ctrl.programsSelected | json}} Current Output: Checked Items: [null,true,true,true,null,true, ...

Discover and analyze quantities across various columns in Excel when certain criteria are fulfilled

Within my data table, each row represents a client and every month I add a new column to indicate the type of orders they placed (A, B, or C). I am seeking to pinpoint clients who have made an order of type A at any point and then later switched to making ...

The d3.js Time Scale Chart is facing issues when rendering with Array object values, unlike static values which render the chart perfectly

Generating an Array Dynamically with N objects from a JSON File var taskArray = []; d3.json("input.json", function(error, json) { if (error) return console.warn(error); for ( var i = 0; i < json.length; i++) { ...

Monitor the true/false status of each element within an array and update their styles accordingly when they are considered active

Currently, I am attempting to modify the active style of an element within an array. As illustrated in the image below - once a day is selected, the styles are adjusted to include a border around it. https://i.stack.imgur.com/WpxuZ.png However, my challe ...

Combining conditions and CSS classes within the ngClass directive in Angular

Is it possible to combine a condition and a class within the same "ngClass" in Angular? [ngClass]="{cssclass1 : object.cssclass1status , object.cssclass2}" The condition (bold) and CSS class (italic) can be used together. Previously, I have implemented t ...

Is it possible to locate a Typescript class only when there are no references to its properties?

Currently, I am utilizing TypeScript 2.0 within VSCode and although the highlighted errors are being confirmed by the TypeScript compiler, they all point to a module that I am importing: import * as els from 'elasticsearch'; The module elastics ...

Whenever signing in with Next Auth, the response consistently exhibits the values of "ok" being false and "status" being 302, even

I am currently using Next Auth with credentials to handle sign-ins. Below is the React sign-in function, which can be found at this link. signIn('credentials', { redirect: false, email: email, password: password, ...

Restrict results according to values post-merge activity - MongoDB

In my database, I have two collections structured as follows: Collection 1 { "_id": "col1id1", "name": "col1doc1", "properties": [ "<_id1>", "<_id2>", "<_id3>"] } Collection 2 { "_id": "<_id1>", "name": "doc1 ...

transferring an array of structs to a CUDA kernel

Currently, I am tackling a project that requires sending a struct array to a CUDA kernel. The struct in question also includes an array. In order to test this functionality, I have developed a basic program. struct Point { short x; short * ...

Having trouble properly removing an item from an array using splice() function

I'm facing an issue with an array where I need to remove a specific object. I attempted using the splice() method, but upon implementation, it ends up removing all objects except the one that was found. Here's a snippet of my JavaScript code: On ...

Quietly renewing leads to OAuthErrorEvent with the type "silent_refresh_timeout" and no information on the reason or params

Upon calling the connect/authorize endpoint for silent renew, it triggers the silent_renew.html file. However, the log is showing an OAuthErrorEvent with type: "silent_refresh_timeout", reason: null, params: null. I am utilizing an angular client with the ...

Protecting API Key in Angular 2

After spending more than a day searching on Google, I may not be using the right keywords to find the answer I need. Here is my current setup: I have an ExpressJS API running with pm2 on port 3000 An Angular 2 app being served via nginx Both of these a ...

The <g> tag fails to properly render within the <svg> element in Firefox

When running an Angular 6 application with ES6-style D3js modules, there are some issues on Firefox (Chromium, Chrome, Safari, and IE Edge work fine). Below is a sample of pseudo code (full production code is available below): <svg width="500" height=" ...

Ways to display the SearchFilter textbox in an Angular Multiselect Dropdown, even when there are no items loaded

Angular version: 8 ng-multiselect-dropdown version: ^0.2.10 I am facing a situation where the user needs to start typing in the search field to load results dynamically into the dropdown. However, in the ng-multiselect-dropdown component, the search box ...

Scrolling horizontally in Ionic framework

In regards to the response found on Ionic - Horizontal scroll tab for Categories, I have a question. I am curious about what needs to be included in the category.model. Can anyone provide some guidance? ...

Simply drag and drop the image from your browser window into the file input

Is there a way to drag an image from a browser window into a file input that I developed? Looking for assistance in creating an event that allows me to get the image when dragging it to an input. While I have successfully created an event to obtain the i ...