• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

84
Views
fetch data from the Json file use local variable as a key
const quizData = [{
        question: "Which of the following purpose, JavaScript is designed for ?",
        a: 'To Execute Query Related to DB on Server',
        b: 'To Style HTML Pages',
        c: ' To Perform Server Side Scripting Opertion',
        d: ' To add interactivity to HTML Pages.',
        correct: 'd'
    },
    {
        question: "how old is adnan?",
        a: '10',
        b: '20',
        c: '30',
        d: '40',
        correct: 'c'
    }]

The above is a quiz data. I want to get only the value of key that is in key 'correct' value. Like in first question the correct answer is 'd' so I only want to get the value of key 'd'.

I tried this code but it gave undefined answer

let rs = quizData[0].correct

console.log(quizData[0].question + "\n" + quizData[0].rs)
almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can use code like this:

function getCorrectAnswerAtIndex(data, index) {
  const item = data[index]
  return item[item.correct]
}

Usage:

// get answer at 0
console.log(quizData[0].question + '\n' + getCorrectAnswerAtIndex(0))
almost 3 years ago · Juan Pablo Isaza Report

0

Looks like you're trying to figure out how to access an object's properties when the name of the property is stored in a variable (instead of hardcoded).

The follow 3 bits of code all get the same value out of myObj:

myObj.myKey

or

myObj['myKey']

or

const myDynamicKey = 'myKey';

myObj[myDynamicKey]

So the follow should work for you in this case:

const quizData = [{
    question: "Which of the following purpose, JavaScript is designed for ?",
    a: 'To Execute Query Related to DB on Server',
    b: 'To Style HTML Pages',
    c: ' To Perform Server Side Scripting Opertion',
    d: ' To add interactivity to HTML Pages.',
    correct: 'd'
}, {
    question: "how old is adnan?",
    a: '10',
    b: '20',
    c: '30',
    d: '40',
    correct: 'c'
}];

const correctLetter = quizData[0].correct;

console.log(quizData[0].question + "\n" + quizData[0][correctLetter]);

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error