Wonka Wonka - 2 months ago 43
Javascript Question

MobX - Retrieve index of observable array object?

When narrowing down a selection to a single object in an observable array, how can I get that object's index efficiently?

@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

Answer

You could use the 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));