[英]How to check if javascript array holds property with specific value, if so returns true
I have a select - option in angular, and I need to check values that have same id as id in database, so I have tried something like this: 我在角度中有一个select-选项,我需要检查与数据库中的id具有相同id的值,因此我尝试了以下操作:
isDropdownValueSelected(amf: ApplicationModuleForm): boolean {
for (let i = 0; i < this.role.applicationForms.length; i++) {
if (this.role.applicationForms[i].id == amf.id) {
return true;
}
else {
return false;
}
}
}
My angular part: 我的棱角分明:
<div class="col-lg-9">
<select id="applicationModuleFormSelect" name="applicationModuleFormSelect" class="form-control multiselect-select-all" multiple="multiple" data-fouc>
<option *ngFor="let amf of appModuleForms;" [value]="amf.id" [selected]="isDropdownValueSelected(amf)">{{amf.title}}</option>
</select>
</div>
So basically there I wanted to loop for each id in option and if I found similar in my array I would return true, because array this.role.applicationForms
holds values from database, but unfortunatelly this does not works, nothing is selected in dropdown and I tested with console log it says only 1 value exist even if there are 3.. 因此,基本上,我想为选项中的每个id循环,如果我在数组中发现相似的对象,我将返回true,因为数组
this.role.applicationForms
保留了数据库中的值,但不幸的是,这不起作用,下拉菜单中未选择任何内容,我测试了控制台日志,它说即使存在3,也只有1个值。
Thanks guys Cheers 谢谢大家的欢呼
Maybe you need to move the false value to the end for returning, because every return
statement ends the function. 也许您需要将false值移到末尾才能返回,因为每个
return
语句都会终止该函数。
isDropdownValueSelected(amf: ApplicationModuleForm): boolean {
for (let i = 0; i < this.role.applicationForms.length; i++) {
if (this.role.applicationForms[i].id == amf.id) {
return true;
}
}
return false;
}
This function only works when the id of the first element is matched, because you're returning the value on every check. 仅当第一个元素的ID匹配时,此函数才起作用,因为您每次检查都会返回该值。
You should update the code to be like this: 您应该将代码更新为如下形式:
isDropdownValueSelected(amf: ApplicationModuleForm): boolean {
for (let i = 0; i < this.role.applicationForms.length; i++) {
if (this.role.applicationForms[i].id == amf.id) {
return true;
}
}
return false;
}
Use the some
operator instead of looping on your elements: 使用
some
运算符而不是在元素上循环:
isDropdownValueSelected(amf: ApplicationModuleForm): boolean {
return this.role.applicationForms.some(e => e.id === amf.id);
}
You do not need for
loop: 你不需要
for
循环:
isDropdownValueSelected(amf: ApplicationModuleForm): boolean {
if (this.role.applicationForms.find(x => x.id == amf.id)) {
return true;
}
else {
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.