[英]Angular iterate an array with two conditions
I have this array and these values:我有这个数组和这些值:
levels$: Observable<any[]> = [
{
name: 'first level primary school'
},
{
name: 'second level primary school'
},
{
name: 'first level secondary school'
}
]
const isPrimarySchool = false
const isSecondarySchool = false
And I want to iterate the array and find if there is a string with the word 'primary' or 'secondary' (it could be both), and turn the value of isPrimarySchool or isSecondarySchool to true, or both if it's the case.我想迭代数组并查找是否有一个带有单词“primary”或“secondary”的字符串(它可能是两者),并将 isPrimarySchool 或 isSecondarySchool 的值设置为 true,或者两者都设置为 true。
The method that I found to resolve this, is this one:我发现解决此问题的方法是:
this.levels$.subscribe(levels =>
levels.forEach(level => {
if (level.name.toLowerCase().includes('primary') {
this.isPrimarySchool = true
}
if (level.name.toLowerCase().includes('secondary')) {
this.isSecondarySchool = true
}
})
)
Is there a better way to resolve the two 'if' parts, using lodash or normal javascript?有没有更好的方法来解决两个“if”部分,使用 lodash 或普通 javascript?
this.levels$.subscribe(levels =>{
this.isPrimarySchool =levels.some(level => level.name.toLowerCase().includes('primary'));
this.isSecondarySchool = levels.some(level => level.name.toLowerCase().includes('secondary'));
})
You could use If/Else instead of 2 Ifs, and use a 3rd else.您可以使用 If/Else 而不是 2 个 If,并使用第 3 个 else。
Remember that using If/elsif/else will be less costly than adding 2 If's.请记住,使用 If/elsif/else 将比添加 2 个 If 成本更低。
Or, you could ternary operators but that's most likely not a better approach.或者,您可以使用三元运算符,但这很可能不是更好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.