#javascript #arrays #reactjs #object
Вопрос:
Как я могу указать «истинное» значение в этом объекте:
const questions = [
{
questionText:
'this is question 1',
answerOptions: [
{ answerText: 'answer1', isCorrect: false },
{ answerText: 'answer2', isCorrect: false },
{ answerText: 'answer3', isCorrect: true },
{ answerText: 'answer4', isCorrect: false },
],
}
]
Комментарии:
1. вопросы.Варианты ответов[2].Исправьте
Ответ №1:
const questions = [
{
questionText:
'this is question 1',
answerOptions: [
{ answerText: 'answer1', isCorrect: false },
{ answerText: 'answer2', isCorrect: false },
{ answerText: 'answer3', isCorrect: true },
{ answerText: 'answer4', isCorrect: false },
],
}
]
let allCorrects = [];
// You can use this code block
allCorrects = questions.map(x => x.answerOptions.filter(y => y.isCorrect));
console.log(allCorrects)
Ответ №2:
Вы можете просто использовать метод фильтра в js , и он возвращает массив истинных значений.
const questions = [
{
questionText:
'this is question 1',
answerOptions: [
{ answerText: 'answer1', isCorrect: false },
{ answerText: 'answer2', isCorrect: false },
{ answerText: 'answer3', isCorrect: true },
{ answerText: 'answer4', isCorrect: false },
],
}
]
const result = questions[0].answerOptions.filter(answer => answer.isCorrect )
console.log(result)