javascript - how deep can .find go
问题描述
I know I can use find easily like
answers.find(question => question.questionId === displayingQuestionId)
but my structure is:
answers: [
{questionId: 0000,
answers: [{title: 'answer1'},{title: 'answer2'}]
]
so how can I use find in this:
where I want to find the questionId that matches the questionId for the answers
I realise this is quite confusing
answers.find(question => question.answers.questionId === displayingQuestionId)
something like that ^ except that is not working...
解决方案
所以基本上你可以得到你想要的深度。但是您不能只使用 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')));
推荐阅读
- python - Python中的简单状态机
- react-native - “react-native run-android --variant=release” 删除 index.android.bundle 然后在 ENOENT 上为同一个文件失败?
- mysql - 多个插入和选择到单个查询中
- python - 我在 Python 中无法理解这段代码
- bixby - 如何在 Bixby 中实现点击缩放功能?
- linux - Linux 时区警告
- python - 如何仅读取和剥离特定的代码行?
- java - Spring Boot - 验证请求正文 json 键
- flutter - 使用 StreamBuilder 为 CustomScrollView 构建 SliverList
- dockerfile - 用于在 CentOS 7 上运行 Splunk 的 DockerHub 标记