MobX - 检索可观察数组对象的索引?

时间:2016-09-19 17:58:10

标签: javascript mobx

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

@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

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

相关问题