What is the best way to extract a specific value from a line of data using JavaScript (JSON)?

My current task involves extracting the "correctAnswers" from a specific number.

Let's take a look at this JSON example:

{
  "questions": [
    {
      "number": 3,
      "question": "☀️ ➕ 🌼 = ?",
      "answers": [
        "🌻sunflower",
        "BIRTHDAY",
        "iPhone",
        "MOON CAKE"
      ],
      "correctAnswers": [
        "🌻sunflower"
      ],
      "random": true,
      "timeLimit": "24"
    },
    {
      "number": 1,
      "question": "⭐️ ➕ 🐟 =❓ ",
      "answers": [
        "STAR FISH",
        "iPhone",
        "MOON CAKE",
        "HOT DOG"
      ],
      "correctAnswers": [
        "STAR FISH"
      ],
      "random": true,
      "timeLimit": "20"
    },
    {
      "number": 7,
      "question": "👁 ➕ ☎ = ",
      "answers": [
        "SUNGLASSES",
        "SUNFLOWER",
        "HOUSEPAINT",
        "IPHONE"
      ],
      "correctAnswers": [
        "IPHONE"
      ],
      "random": true,
      "timeLimit": 15
    },
  ]
}

I am currently working on a solution to extract the "correctAnswers" for the number 1, or any random number within the "questions" array.

Answer №1

const questionsArray = {
  "questions": [
    {
      "number": 3,
      "question": "⭐️ ➕ 🌼 = ?",
      "answers": [
        "🌻sunflower",
        "BIRTHDAY",
        "iPhone",
        "MOON CAKE"
      ],
      "correctAnswers": [
        "🌻sunflower"
      ],
      "random": true,
      "timeLimit": "24"
    },
    {
      "number": 1,
      "question": "⭐️ ➕ 🐟 =❓ ",
      "answers": [
        "STAR FISH",
        "iPhone",
        "MOON CAKE",
        "HOT DOG"
      ],
      "correctAnswers": [
        "STAR FISH"
      ],
      "random": true,
      "timeLimit": "20"
    },
    {
      "number": 7,
      "question": "👁 ➕ ☎ = ",
      "answers": [
        "SUNGLASSES",
        "SUNFLOWER",
        "HOUSEPAINT",
        "IPHONE"
      ],
      "correctAnswers": [
        "IPHONE"
      ],
      "random": true,
      "timeLimit": 15
    },
  ]
};

const { questions } = questionsArray;

// Get correct answers by question number
const findCorrectAnswersByNumber = qNumber => {
  const selectedQuestion = questions.find(({ number }) => number === qNumber);
  if (!selectedQuestion) {
    return false;
  }

  return selectedQuestion.correctAnswers;
};
console.log(findCorrectAnswersByNumber(3)); // Correct answers for question with number 3

// Randomly select a question and get its correct answers
const randomCorrectAnswers = questions[Math.floor(Math.random() * questions.length)].correctAnswers;
console.log(randomCorrectAnswers);

Answer №2

Click a button to select a question at random, then display its properties.

var data = {
  "questions": [
    {
      "number": 3,
      "question": "☀️ ➕ 🌼 = ?",
      "answers": [
        "🌻sunflower",
        "BIRTHDAY",
        "iPhone",
        "MOON CAKE"
      ],
      "correctAnswers": [
        "🌻sunflower"
      ],
      "random": true,
      "timeLimit": "24"
    },
    {
      "number": 1,
      "question": "⭐️ ➕ 🐟 =❓ ",
      "answers": [
        "STAR FISH",
        "iPhone",
        "MOON CAKE",
        "HOT DOG"
      ],
      "correctAnswers": [
        "STAR FISH"
      ],
      "random": true,
      "timeLimit": "20"
    },
    {
      "number": 7,
      "question": "👁 ➕ ☎ = ",
      "answers": [
        "SUNGLASSES",
        "SUNFLOWER",
        "HOUSEPAINT",
        "IPHONE"
      ],
      "correctAnswers": [
        "IPHONE"
      ],
      "random": true,
      "timeLimit": 15
    },
  ]
};


// Pick a random question
let question = data['questions'][Math.floor(Math.random() * data['questions'].length)];


console.log(question.question, question.correctAnswers)

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

"Permission denied to access restricted URI" error encountered while attempting to utilize ng-template functionality

I am attempting to implement ng-include for recursive templates in my HTML. After testing it on jsfiddle and confirming that it works, I tried the same locally. However, I encountered the following error: Error: Access to restricted URI denied createHttpB ...

Unraveling intricate JSON structures into DataFrames using Julia

I'm in the process of translating some Python code into Julia and I'm facing a challenge with reading nested JSON data into a DataFrame. Is there an easy way to accomplish this in Julia? Here's my current Julia code: r = HTTP.get(url_instru ...

Is the username you want available?

I am facing a challenge in my registration form validation process where I need to verify the username input using javascript and flask in python, but the implementation is unclear to me. The requirement is to utilize $.get in the javascript segment along ...

Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2) Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now ...

Creating an element in JavaScript with a designated ID is a

I'm working on creating a JavaScript array that holds 3 elements: var employees = [ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] To iter ...

What is the best way to reset an angularJS form after it has been submitted

I am trying to figure out a way to clear form fields on a modal window after the user executes the save method. I have attempted using $setPristine in AngularJS, but it's not working as expected. Any suggestions on how to achieve this task? Here is t ...

It is advised not to use arrow functions to assign data when fetching API data with axios in Vue.js 2

Trying to retrieve data from a URL using Axios in my Vue app is resulting in the error message: Error: Arrow function should not return assignment Complete error message: Error: Arrow function should not return assignment (no-return-assign) at src\co ...

Reactjs button only responds on the second click instead of the first tap

Currently, I am working on a Reactjs/nextjs project and have a video with audio button on my page. There are two things that I want to achieve: 1) I would like the button to have the "bi bi-volume-mute" class by default instead of "bi bi-volume-down". 2) W ...

What's the secret behind generating a crisp 400 on paper?

Understanding Why it Prints 400 I'm struggling to comprehend the logic behind this var x = {}, y = { key: "y" }, z = { key: "z" }; x[y] = 100; x[z] = 200; console.log(x[y] + x[z]); ...

Leveraging jQuery to extract a key-value pair and assign it to a new property by

I'm struggling with extracting a value from a key-value pair and inserting it into the rel property of an anchor tag. Even though I try to split the code and place the value correctly, it doesn't seem to work as expected. Instead of applying the ...

javascript code for subtracting values in arrays

I am facing a scenario where I have 3 arrays of the same length. My requirement is to automatically subtract the values in the first two arrays without any user input. If the result of subtraction is negative, I need to identify the index of that array num ...

Challenges with sending JSON encoded Arrays from WordPress to PHP results in empty or NULL responses

My Plugins site has multiple Inputs that I need to gather values from and push them into an array. Then, I utilize the jQuery.post method to send this data to my PHP script. Javascript: var json = JSON.stringify(output); // output is an array with multip ...

Leveraging the outcome of a for loop in order to set a condition within an else if statement

How can I condition my third else if statement based on the result of a for loop? //If player clicks centre on first move go in corner square if (current[4] === playerToken && this.state.stepNumber === 1) { let move = c ...

Functionality fails to load correctly post completion of AJAX request

After successfully implementing an API call to OS Maps (UK map builder) as per their documentation, I encountered a problem when trying to display a map based on a custom field name using ACF (Advanced Custom Fields) in WordPress. The issue arises because ...

I initially had ngRoute set up in my app, but decided to make the switch to ui-router. However, now it seems like

I currently have an application set up using express and angular. I decided to transition to ui-router in order to utilize multiple views, but it doesn't appear to be functioning as expected. app.js app.use(express.static(path.join(__dirname, ' ...

Incorporating External HTML Content Using JQuery Function

Looking for assistance with a JQuery function: function addSomeHTML() { $("#mysection").html("<div id='myid'>some content here</div>"); } I am trying to have this part: <div id='myid ...

How can we determine if a Node.js application will remain operational?

How is the longevity of a Node.js app determined? For example, consider this code snippet: console.log('Hello World'); In this case, the phrase will be printed and the app will exit immediately. However, with a web server that is actively lis ...

Discovering the window.scrollTop, ScrollY, or any other distance value while utilizing CSS scroll snap can be achieved by following these

I am currently utilizing css scroll snap for smooth scrolling through sections that are 100vh in height. The functionality of the scroll snap is quite impressive. However, I need to find a way to determine the exact distance the user has scrolled down the ...

A guide on transferring radio button values to another program and saving them into a database with the help of PHP and jQuery

I have encountered an issue with storing radio button values in a database. Specifically, I want to assign the value of 1 for "Yes" and 0 for "No". To accomplish this, I am utilizing two scripts - a.php and b.php. The former obtains the radio button values ...

The hamburger icon seems to be frozen and unresponsive

I'm struggling to get my hamburger icon to reveal the navigation bar when clicked. The icon itself functions properly and adapts to different screen sizes, but the overlay remains stationary. Check out my code on JSFiddle! <html> <head> ...