Is it possible to compare the values of two objects within an array?

Is there a way to check for equality between two objects within an array?

In my website, I have a quiz with various input questions. The user's responses are stored in an array along with the question and correct answer.

Here is an example of the array structure:

var questions = [
    [{
      "q": "What is the capital of England?",
      "ans": "london",
      "userinput": "london"
    }, {
      "q": "What is the capital of Ireland?",
      "ans": "dublin",
      "userinput": "dublin"
    }, {
      "q": "What is the capital of France?",
      "ans": "paris",
      "userinput": "paris"
    }, {
      "q": "What is the captial of Spain?",
      "ans": "london",
      "userinput": "madrid"
    }],
    ...

I am having trouble figuring out how to write the comparison if statement. When I attempted it, I received a console message saying SyntaxError: Unexpected token {.

I also want to include [$slide] and [$qnum] for code reusability on other pages.

if ($(questions[$slide][$qnum].userinput.val()) === $(questions[$slide][$qnum].ans.val())
...

Answer №1

There is no need for jQuery in this situation. To solve the problem, you must identify the question within the array using the index and then access the userinput and ans properties of the question object.

if( questions[$slide][$qnum].userinput === questions[$slide][$qnum].ans )

For instance:

var questions = [
    [{
        q         : "What is the capital of England?",
        ans       : "london",
        userinput : "london"
    }]
];

if( questions[0][0].userinput === questions[0][0].ans ) {
    console.log("match");
}

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

Identify matches between two sets of data by comparing each row, cell by cell

I am working with two tables, one for females and one for males, both containing presence-absence data. I am interested in conducting pairwise comparisons between the two tables on a cell-by-cell basis to identify the number of cells shared by each pair (w ...

Tips for accessing a file in AngularJS

Can AngularJS be used to read files? I am interested in placing the file within an HTML5 canvas for cropping purposes. I was considering implementing a directive. Below is the JavaScript code that I plan to include in my directive: function readURL(input ...

The issue I am facing is that CKEditor is inserting the <pre> tag into my

I have been attempting to input Hindi language content into my database. However, when I make an API request, the data is added in Hindi as needed but a <pre> tag is inserted. I am using CkEditor like this: <CKEditor data={this.stat ...

Tips for refreshing the <img> tag using a user image

I am currently designing a bootstrap webpage and trying to implement a feature where the user can input an image, which will then be displayed in a preview modal along with some text provided by the user. The modal is functioning correctly. Here is the co ...

Should case sensitivity be disregarded in an array's input?

I need to search for a value in an array, but the search should be case-insensitive. How can I achieve this? This is the code snippet I am using: $.ajax({ type: "GET", url: "ajax.php", dataType: "json", data: { pageType: pageType, input: request.term, da ...

Ways to choose the correct css styling

I'm currently working on creating navigation using Bootstrap 4, but I've hit a roadblock in adjusting the li items to suit my navigation needs. I'm struggling to figure out how to select these li tags since they are nested in multiple classe ...

Utilizing Ajax for Multiplication

Is there a way to dynamically calculate and display the total amount by multiplying the unit price with the quantity entered in the text box as it changes? <div> <label id="" name="price" class="unitprice"><?php echo "Price: <label ...

Is web analytics done via client-side (JavaScript) or server-side logging on websites?

As I embark on creating a web application to track web statistics for my clients, I've run into a dilemma. With the rise of ajax usage, I'm unsure whether it's best to log a user visit using JavaScript or serverside. Additionally, I'm u ...

The web application encountered an error: "Uncaught TypeError: Cannot read property 'map' of undefined" when trying to retrieve

Struggling with a simple API fetch, and despite checking everything multiple times, I can't seem to figure out what's going wrong. It feels like I'm missing something crucial. import { useState } from "react"; import ProductCard fr ...

Limiting character count in jQuery using JSON

I am trying to manipulate the output of a snippet of code in my jQuery: <li> Speed MPH: ' + val.speed_mph + '</li>\ that is being pulled from a JSON endpoint and currently displays as: Speed MPH: 7.671862999999999 Is there a ...

Waiting for Promise Js to be fulfilled

I've been exploring the use of Bluebird for handling promises in Node.Js. I have encountered a situation where I need a function to return only when a promise is fulfilled. The desired behavior can be illustrated by the following code snippet: functi ...

Attempting to trigger the timer to begin counting down upon accessing the webpage

Take a look at this example I put together in a fiddle: https://jsfiddle.net/r5yj99bs/1/ I'm aiming to kickstart as soon as the page loads, while still providing the option to pause/resume. Is there a way to show the remaining time as '5 minute ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

Are there any JavaScript libraries available that can mimic SQLite using localStorage?

My current application makes use of SQLite for storage, but I am looking to switch it up to make it compatible with Firefox and other browsers. I've been considering localStorage as an option. However, I've noticed that localStorage lacks some o ...

The datepicker function is malfunctioning in a div that has been dynamically loaded through

I am experiencing an issue with loading a div populated by ajax. The datepicker does not seem to be called when the content is loaded this way. Initially, I had the datepicker loaded in the header of the main page, but even after trying to load it within ...

Decipher the JSON data for a Facebook cover photo

I am utilizing the Facebook Graph API to retrieve the user's cover picture. By accessing the link provided at , a JSON object containing the picture link is returned. How can I fetch this link using JQuery or JavaScript? Here is my attempt: HTML: & ...

What's the best way to trigger an event within a tag in a Vue.js component?

app.js Vue.component("popup",{ template : /*html*/` <div class="popup is-active" > <div class="popup-background"></div> <div class="popup-card"> <header class=" ...

Obtain information from a CSV document within Highchart Angular

Is there a way to access and retrieve data from a CSV file stored in the assets folder of my local system? The CSV file contains 5 or 6 columns of information. Important: This is an Angular project, therefore jQuery is not available. ...

Transitioning from mui version 4 to version 5 leads to an error message: "TypeError: Cannot access 'keyboardDate' properties of undefined"

After updating from MUI v4 to version v5, I encountered failing tests with the following error: TypeError: Cannot read properties of undefined (reading 'keyboardDate') 17 | it("should render correctly without any errors", () =& ...

Utilitarian pool method yields the output from the specified callback function

As a beginner in nodejs, I am currently experimenting with generic-pool and mariasql. My code is functioning well. However, I recently enclosed my code within a function, and I am unsure about the proper way to handle events in nodejs to retrieve the resul ...