当将选择范围缩小到可观察数组中的单个对象时,如何有效地获得该对象的索引?
@observable questionsList = [{
id: 1,
question: "Is the earth flats?",
answer: "Some long answer here..."
}, {
id: 2,
question: "Does the moon have life?",
answer: "Some long answer here..."
}];
const quesitonId = 2;
const question = this.questionsList.find(q => q.id === questionId);
const questionIndex = // should be 1
答案 0 :(得分:10)
您可以使用findIndex:
questionsList.findIndex(q => q.id === 2);
var questionsList = [{
id: 1,
question: "Is the earth flats?",
answer: "Some long answer here..."
}, {
id: 2,
question: "Does the moon have life?",
answer: "Some long answer here..."
}];
console.log(questionsList.findIndex(q => q.id === 2));