如何根据特征过滤JSON数组并输出正确选项的索引
Find the Index of the Correct Answer in Your Array
Got it, let's break down how to solve this. You've got a parsed array of option objects, and you need to find the index of the one where correct: true — here are the most straightforward ways to do it.
Method 1: Use Array.findIndex() (Most Concise)
This built-in array method is made exactly for this scenario: it returns the index of the first element that matches your condition.
// Your parsed array from JSON const options = [ { correct: false }, { correct: true }, { correct: false }, { correct: false } ]; // Find the index of the correct answer const correctAnswerIndex = options.findIndex(option => option.correct === true); // Output the result console.log(`The correct answer is: ${correctAnswerIndex}`);
Notes:
- If no element with
correct: trueexists,findIndex()returns-1. You can add a quick check for this edge case:if (correctAnswerIndex !== -1) { console.log(`The correct answer is: ${correctAnswerIndex}`); } else { console.log("No correct answer found in the array."); }
Method 2: Manual Loop with forEach()
If you prefer a more explicit approach, you can iterate through the array and track the index manually:
let correctAnswerIndex = -1; const options = [ { correct: false }, { correct: true }, { correct: false }, { correct: false } ]; options.forEach((option, index) => { if (option.correct === true) { correctAnswerIndex = index; } }); // Output the result if (correctAnswerIndex !== -1) { console.log(`The correct answer is: ${correctAnswerIndex}`); }
This works just fine, but findIndex() is more idiomatic and concise for this specific task.
内容的提问来源于stack exchange,提问作者TBG
相关产品推荐
相关产品推荐

