Home > Mobile >  React.js Targetting a value in object
React.js Targetting a value in object

Time:09-22

How can I target the 'true' value in this 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 },
      ],
    }
]

CodePudding user response:

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)

CodePudding user response:

You can just use filter method in js , and it returns an array of truthy values.

    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)  

  • Related