admin管理员组

文章数量:1332383

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

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
Share edited Sep 19, 2016 at 18:04 Tholle 113k22 gold badges208 silver badges197 bronze badges asked Sep 19, 2016 at 17:58 WonkaWonka 8,68422 gold badges82 silver badges126 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

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

本文标签: javascriptMobXRetrieve index of observable array objectStack Overflow