【问题标题】:how deep can .find go.find 能走多深
【发布时间】:2018-05-21 16:41:21
【问题描述】:

我知道我可以轻松地使用 find

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

但我的结构是:

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

那么我该如何使用 find 呢:

我想在哪里找到与答案的 questionId 匹配的 questionId

我意识到这很令人困惑

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

类似的东西 ^ 除了那不起作用...

【问题讨论】:

  • 第一个适合您拥有的结构,除非您想匹配其中一个 answers.answers 中的属性,或者您没有显示完整的数据深度
  • find 可能不是执行此操作的函数,因为即使您可以使用检查内部数组的条件,它也只能从顶部杠杆数组返回一个元素。
  • “我想找到与 questionId 相匹配的 questionId 作为答案”你能举个例子来说明你试图实现的目标吗?
  • 显示您实际要搜索的对象。您展示了一个带有答案的对象,但它们只有标题。你在找什么?

标签: javascript arrays reactjs find


【解决方案1】:

所以基本上你可以随心所欲地获得属性。但是您不能只使用 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')));

【讨论】:

    猜你喜欢
    • 2011-05-29
    • 2011-01-20
    • 1970-01-01
    • 2023-03-11
    • 2010-09-05
    • 2019-12-13
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多