javascript - 迭代嵌套数组,es6方式,我已经使用foreach完成了
问题描述
我已经使用 forEach 完成了迭代,代码正在运行,但请你建议它是否可以以 es6 方式完成,并且我的实现是否正确
我已经完成了迭代,代码可以工作,但是我想知道更流畅的方法以及这种实现是否正确
var arrayToBeChecked =
[
{ name: "one",
objectvalue : {
first : ['valueIamNotInterestedIn0'],
second :'valueIamNotInterestedIn1'
}
},
{ name: "two",
objectvalue : {
first : ['valueIamLookingFor'],
second :'valueIamNotInterestedIn5'
}
},
{ name: "three",
objectvalue : {
first : ['valueIamNotInterestedIn5'],
second :'valueIamNotInterestedIn5'
}
}
]
var checkBoolean = false;
arrayToBeChecked.forEach(val => {
let selectedArray = val.objectvalue['first']
if(selectedArray.indexOf('valueIamLookingFor') > -1){
checkBoolean = true
}
})
console.log(checkBoolean)
解决方案
ES6 方法是首先将数组映射到您只感兴趣的值。然后使用some
Array 方法查找是否有任何项目通过您的条件。
indexOf
此外,您可以使用includes
which 返回布尔值来代替。
const checkBoolean = arrayToBeChecked
.map(({ objectvalue }) => [...objectvalue.first, objectvalue.second ])
.some(v => v.includes('valueIamLookingFor'));
推荐阅读
- reactjs - 找不到 npm 命令 - reactjs
- r - 如何在 R 中的 excel 文件上使用 get_sentences()?
- java - 如何在另一个线程中绘制() JFrame?
- javascript - Vercel 巧妙的设置
- java - volatile 关键字是否保证读取器线程读取的最新值?如果不是,它的用途是什么?
- logging - 没有制作 Jboss Audit.log 文件
- python - 在 VSCode 中调试 Jinja2 模板
- python - rarfile 给出 BadRarFile: Failed the read enough data 错误
- python - 按升序按值和按降序按键对字典进行排序
- python - 如何在 python 的任何数据结构中检查 NaN?