Reputation: 8674
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
Upvotes: 2
Views: 2280
Reputation: 112787
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));
Upvotes: 11