{
questionText: 'What is 4 5?',
answerOptions: [
{ answerText: '14', isCorrect: false },
{ answerText: '9', isCorrect: true },
{ answerText: '11', isCorrect: false },
{ answerText: '20', isCorrect: false },
],
},
I have this javascript object. How can I render the correct option, in this case "9"?
{questions.map((answerOption) =>
answerOption.answerOptions.isCorrect ? <div>{answerOption.answerOptions.answerText}</div> : null)}
I tried this, but it's not giving me any output.
CodePudding user response:
Since you don't write it, I guess your object is called questions
.
If in the array you have a single object (like in the example you posted) you have to do something like this:
{
questions.answerOptions.map((answerOption) =>
answerOption.isCorrect ? <div>{answerOption.answerText}</div> : null)
}
Otherwise, if you have more than one object inside the array, you can put two map
one inside the other:
{
questions.map((answerOption) =>
answerOption.answerOptions.map(el =>
el.isCorrect ? <div>{el.answerText}</div> : null)
)
}
CodePudding user response:
Your answerOptions
is an array, so you will need to iterate over that as well. You can use the Array#find()
method to find the element where isCorrect
is true
:
function App() {
let questions = [
{
questionText: 'What is 4 5?',
answerOptions: [
{ answerText: '14', isCorrect: false },
{ answerText: '9', isCorrect: true },
{ answerText: '11', isCorrect: false },
{ answerText: '20', isCorrect: false },
],
}
];
return (
<div>
{questions.map((question) => {
let answer = question.answerOptions.find((i) => i.isCorrect);
if (!answer) {
console.log('Ooops, no way');
}
return (
<p>
The correct answer for "{question.questionText}" is <b>{answer.answerText}</b>
</p>
);
})}
</div>
);
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
<div id="root"></div>
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
- Using
Array#flatMap
, iterate over thequestions
. For every questions, get the correctanswerOptions
usingArray#filter
. This would result in an array of correct answer options. - Using
Array#map
, iterate over this array and render theanswerText
{
questions.flatMap(({ answerOptions = [] }) =>
answerOptions.filter(({ isCorrect }) => isCorrect)
).map(({ answerText }) => <div>{answerText}</div>)
}
CodePudding user response:
I think you're after something like this:
{questions.answerOptions.filter(option=>option.isCorrect).map(answer=><div>answer.answerText</div>)}