Getting a precise element from an array in JSON using Angular 5

I've been struggling to fetch a specific value ("isRight") from a JSON object. I have tried multiple solutions found on stackoverflow and even compared my code with one of them, but I keep getting the value as undefined without any errors.

{

        "QuestionID" : "1",
        "Question"   :"The ozone layer restricts: ",
        "OP"         :["X-rays and gamma rays" , 
                       "Visible light", 
                       "Infrared radiation", 
                       "Ultraviolet radiation" ],
          "isRight"  :"Ultraviolet radiation"

    },


    {


        "QuestionID" : "2",
        "Question"   :"The length of the bridge, which a train 130 metres long and travelling at 45 km/hr can cross in 30 seconds, is:",
        "OP"         :["200 m" , 
                       "225 m", 
                       "245 m", 
                       "250 m" ],
          "isRight"  :"245 m"

    },

.ts:

 filterAnswer(i:number)
      {
      for(i=1 ; i <= this.questArrayNew1.length ; i++)

      {
        console.log(i);
        console.log(this.questArrayNew1);
        this.isRyt  = this.questArrayNew1.find(x=>x.QuestionID == i).isRight;


      }
      }

I am aiming to save the retrieved value in the variable 'isRyt'.

Answer №1

After reviewing the code provided, it appears that the 'QuestionID' is of type string while 'i' is a number. Due to this mismatch in data types, an error similar to

'The '==' operator can not be applied to the 'string' and 'number' types'
is likely to occur. This error has been encountered while testing your code.

To address this issue, it is recommended to compare values of the same data type. It seems that the comparison x=>x.QuestionID == i is failing due to this discrepancy, resulting in an undefined value.

To resolve this problem, consider replacing "QuestionID" : "1" with "QuestionID" : 1.

Upon making this correction, you should obtain the correct isRyt value as shown in this image: https://i.sstatic.net/q2WKA.png

It is believed that this adjustment will yield the expected outcome.

Answer №2

{ 
this.correctAnswer = this.questionArrayUpdated.find(ques =>{
if(ques.Qid === identifier){ return ques.isCorrect }
})}

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

Is it possible to conceal dom elements within an ng-template?

Utilizing ng-bootstrap, I am creating a Popover with HTML and bindings. However, the ng-template keeps getting recreated every time I click the button, causing a delay in the initialization of my component. Is there a way to hide the ng-template instead? ...

Activate an event on a separate webpage using jQuery or JavaScript

Currently, I am in the process of working on a project with 2 distinct pages: Index Settings On the Settings page, I have implemented a button to close an element and hide it. However, I am encountering an issue where I want the elements on the Index pa ...

Calling JavascriptInterface in an H5 environment is not permitted

Utilizing the power of vue, I created an immersive h5 page within the application framework. The seamless connection between the page and the app relies on the use of window.JSInterface for communication. My current challenge lies in invoking the JSInterfa ...

Tips for adding a background image using React refs?

Seeking assistance with setting a background for a specific div using react ref, this is my attempted code snippet: The component class structure as follows: import React from 'react'; import PropTypes from 'prop-types'; import class ...

Next.js application shows 404 errors when trying to access assets within the public directory

I've been struggling to display the favicon for my site (which uses next.js). Despite going through numerous Stack Overflow posts and tutorials, I'm feeling increasingly frustrated. The structure of my project, particularly the public directory, ...

Form with Material-UI's FreeSolo AutoComplete feature

Visit this Sandbox for more details In the provided SandBox example, Material AutoComplete is being used as a multiple input with free options. The component is expected to return ["term1","term2","term3"] to Formik, and each string should be displayed as ...

Replacing Elements in an Array

Currently, I am working on a JSON/HTML generator project aimed at displaying JSON data along with the associated HTML elements for users once they input the required data into the input fields. Despite identifying the issue, I am struggling to come up with ...

How to modify a value in a document within a MongoDB collection

I'm having an issue with updating the 'panel' field in both the cards collection and projects collection. Here is my code snippet: const project = await Project.findOne({"code":currentUser.groupcode}); // this works const ...

Looking for assistance grasping the concept of using a for loop in MongoDB's aggregate method

This code snippet is designed to maintain the order of an array (var list) when utilizing mongoDb's $in clause effectively. Although, I must admit that the logic behind it is not entirely clear to me. I can see that it's iterating in reverse to ...

Having trouble with installing Angular JS on my computer

On my machine, I have successfully installed node.js version v0.12.0. However, when attempting to run sudo npm install, I encountered the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 14.0.0 npm ERR! argv "node" "/usr/ ...

While attempting to retrieve contact details from my mobile device and convert them into JSON format, the app crashes

"This piece of code is responsible for converting data into JSON format." private void convertDataToJSON() { // TODO Auto-generated method stub JSONArray arr = new JSONArray(); try { for(int i=0;i<=contactModel.size( ...

Validator for IP addresses in Angular reactive forms

Hey there, I'm currently trying to implement a validator for an IP address in Angular. Strangely, even when I input an invalid IP address like 12.2.2.2..., the GUI indicates it is valid (as shown in the image). However, the console logs reveal that it ...

embedding fashion within offspring component in vue

Looking to apply inline styles to a child component? I am trying to pass properties like height: 200px and overflow-y: scroll. I attempted passing it this way: <Childcomponent style="height: 200px; overflow-y: scroll;" /> but had no luck. ...

Is it possible to retrieve the promise callback value from outside the function?

From my understanding, callback functions are asynchronous and cannot return a value like regular functions. After learning about promises, I believed that I had a solid grasp of them being an improved version of callbacks that can return values in an asyn ...

Changing the dimensions of a div according to the container's size

I'm currently working on a project that involves an HTML video player with custom Javascript controls, utilizing SVG graphics for the backgrounds. However, I've encountered an issue with using the css calc() function to resize the divs based on t ...

Ensuring Form Integrity through jQuery Validation

I am struggling to customize the errorClass and validClass using JQuery validation. I believe that by adding the .validate function and setting the parameters, it should work. However, even though the validation message displays correctly, the classes re ...

Adding a dynamic key-value pair object to an array using the JS push method

In my programming challenge, I am dealing with an array of objects that have dynamic keys and values. The structure is a bit complicated, but here's a simplified version: let products_row = [ { id: 1, category_id: 11, options: { &a ...

The JavaScript Ajax request appears to be malfunctioning in both Firefox and Google Chrome, however, it seems to be functioning properly

I am currently using JavaScript to make an Ajax request to communicate with an Arduino webserver and dynamically update the content on a webpage. While this functionality has been working smoothly in Safari, I have encountered issues when trying to use it ...

having difficulty sending a post request with Angular

Submitting form data via HTTP post will look like this: saveDataFile(mutlidata,id,value): Observable<Response> { var _url = 'http://xxxx.xxx.xxx'; var saveDataURL = _url + '/' + id; var _this = this; ...

Capture information and store it in a database through the use of AJAX technology

I want to implement AJAX for real-time saving of user input comments directly to the database. Here is where users can input their comments: <div class="comment"> <form action="comment.php"> <textarea cols="35" name="comment ...