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

Having identical functions with varying IDs and the same variable in Ajax is causing issues

Here, I have two HTML rows with different IDs. When the function ItemSearch() is called, I want to display the search results for both IDs. I am new to JavaScript and AJAX. ***1st Html*** <div class="justlauchSearch"> <div class="input-gro ...

How can I incorporate a child component into a separate component within Angular version 14?

Currently working with Angular 14 and facing a challenge with including a child component from another module into a standalone component. The structure of the standalone component is as follows: <div> <child-component></child-component& ...

Error: The Rollup module is unable to locate the 'jquery' file

I've been facing an issue while trying to bundle a vuejs single file component using rollup. The error message that keeps popping up is Module not found: Error: Can't resolve 'jquery'. Despite spending countless hours on this problem, I ...

Why does app.post function while router.post does not seem to work?

I have encountered an issue while logging in with React on the front end. The process goes to my node/Express/Passport backend and I am able to successfully log in when it reaches the backend. However, I am facing difficulties in communicating that informa ...

The jQuery AJAX function executing twice upon click

I've encountered an issue while attempting to make two Ajax calls on a single page using jQuery. The first Ajax call executes successfully and generates the desired results. However, the second Ajax call is meant to be triggered by clicking a button b ...

Connect the CSS active state to a JavaScript event

.el:active{ background:red; } Is there a way to associate the above CSS active state with a JavaScript event, like this: $('.el').on('active', function(){ img.show(); }); I want the image to remain visible when el is presse ...

Guide to generating a JSON file using multiple dictionaries and a single list in Python

I am attempting to organize data into a JSON file with the following structure: [ { "startTimestamp" : "2016-01-03 13:55:00", "platform" : "MobileWeb", "product" : "20013509_825", "ctr" : 0.0150 }, {...} ] The data values are organized as follow ...

Running code sequentially in a Node.js controller

Recently delved into the world of Node.js, and I'm currently tackling the challenge of running this code synchronously in my controller. Quest.js async function create(req, res, next) { const formValue = req.body['form']; ...

Utilize ObjectMapper to parse JSON data into an Object that holds a String and a List of Strings

My scenario involves an Object structured like this: public class Marketplace { private String name; private int id; private List<String> supportedLanguages; } Additionally, I have a Json format input String that loo ...

Having performance issues with an HTML5/JavaScript game on Internet Explorer 8

A new game has been developed using html/javascript. Due to confidentiality reasons, the code cannot be fully shared. The game runs smoothly on most browsers except for IE, which poses a challenge. Compatibility with IE8 is essential, despite its limitati ...

Serializing works fine, but when attempting to deserialize, a MismatchedInputException is thrown

My initial experience with JSON is posing some challenges. While serializing my objects works smoothly, I encounter a MismatchedInputException when attempting to deserialize. The issue arises as Jackson struggles to deserialize an array in my WateringSched ...

In order to comply with JSX syntax rules in Gatsby.js, it is necessary to enclose adjacent elements

I want to apologize beforehand for the code quality. Every time I attempt to insert my HTML code into the Gatsby.js project on the index.js page, I encounter this error: ERROR in ./src/components/section3.js Module build failed (from ./node_modules/gatsb ...

Encrypting sensitive information in JavaScript and Angular 2: SecureString

Is there a way to securely copy sensitive data to the clipboard in javascript/Angular2, ensuring that the string remains confidential by removing it from computer memory when no longer needed? In Microsoft .Net, there is a feature called System.Security.S ...

Anchoring links on a webpage that provide users with a clear indication of their current position within the page

In the scenario of a single-page website with various sections (divs) and a header containing links to different anchors on the page, there is a desire to have an indicator highlight which anchor the user is currently viewing. An example of this can be s ...

Having an issue in Angular 2 where the correct function is not triggered when a button is placed within a selectable anchor

Within an anchor element, I have a button that triggers its own click listener for an editing popup module. The anchor itself has another click listener assigned to it. For example: <a (click)="onClick(myId)" class="list-group-item clearfix"> < ...

Is it more efficient to have a single global event listener or multiple event listeners of the same type in each component for productivity?

This particular mixin is a key component in numerous pages, often appearing in multiple sections within the page. data: () => ({ device: { mobile: false, tablet: false, tabletLand: false, notepad: false deskto ...

The function was triggered upon the form loading, instead of being activated when the button was clicked

The issue I am facing is that in the code snippet below, the function readCSV() is not being triggered when buttons for filepath1 and filepath2 are clicked. The function is only executed on form load. I was expecting it to work on button click as well. I ...

Creating a dynamic trio of graphs with HTML5, CSS3, and Vanilla JavaScript

I successfully created a tree graph using HTML5 and CSS3, but currently the nodes are static. I am looking to enhance the graph by making it dynamic. By dynamic, I mean that if the number of nodes increases or there are multiple children added, the graph ...

Safari on iOS9 is inaccurately calculating the total sum

My code involves calculating the sum of key/value pairs in a hash within a loop. I have noticed that there is a discrepancy in how the sum is calculated on ios9 Safari compared to other platforms. While I can address this issue for this specific scenario, ...

How can we extract specific data from a JSON file in Python3? I need to retrieve information from the data pool

Recently, I've been delving into extracting data from a JSON file that contains stock information. Coming from a beginner's background in Python, the world of JSON feels quite alien to me. However, I grasp the fundamental concepts and could use s ...