2

将选择范围缩小到可观察数组中的单个对象时,如何有效地获取该对象的索引?

@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
4

1 回答 1

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));

于 2016-09-19T18:02:42.057 回答