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)
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))
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]);