代码之家  ›  专栏  ›  技术社区  ›  The Walrus

你能找到多深。走吧

  •  -2
  • The Walrus  · 技术社区  · 8 年前

    我知道我可以很容易地找到

    answers.find(question => question.questionId === displayingQuestionId)
    

    但我的结构是:

    answers: [
      {questionId: 0000,
       answers: [{title: 'answer1'},{title: 'answer2'}]
    ]
    

    那么我该如何使用find:

    我想找到与答案的questionId匹配的questionId

    我意识到这很令人困惑

    answers.find(question => question.answers.questionId === displayingQuestionId)

    1 回复  |  直到 8 年前
        1
  •  0
  •   Sabik    8 年前

    所以基本上你可以得到你想要的深度。但不能仅使用question.answers.questionId进行正确的比较。 显然,每个循环的.find都会给你提供顶级的对象。你想怎么做就怎么做。

    let arr = [{'questionId': 0000, 'answers': [{'title': 'answer1'},{'title': 'answer2'}]}];
    
    //returns object of the top level if questioned equals to 0
    
    arr.find((answer) => answer.questionId === 0);
    
    //comparison with the internal array elements
    //returns answer if one of the internal answers has title 'answer 1'
    
    arr.find((answer) => !!answer.answers.find((internalAnswer => internalAnswer.title === 'answer1')));