我正在从服务器返回的对象的字段yes
中搜索hhead
的值:
Object.keys(this.data).forEach(key => {
if (this.data[key].hhead === 'yes') {
console.log('Yes '+(this.data[key].hhead === 'yes'))
this.snackBar.open('This household already have ' + this.data[key].far + ' ' + this.data[key].lar + ' (id: ' + this.data[key].iid + ' ) as a head of household', 'Close', {
panelClass: 'error'
});
}
else {
console.log('No '+(this.data[key].hhead === 'no'))
if (data['age'] <= 17 && data['age'] < this.maxAge && (selectedFr == "Head Of Household")) {
let message = 'This individual is not the oldest in his family to be the head of household. Do you want to complete this action ?';
this.openDialog(message, updateType, ind_id, newSts, newMs, newFr, newHH, oldHH, missingData);
}
}
});
此脚本的问题在于if
和else
都是正确的。因此,两个脚本都将运行。
原因是,在第一个条件下,一旦找到yes
值,条件就变为true。
第二个,一旦找到no
,它将运行。
数组类似于:
所以我需要的是如果一个数组在所有行中仅包含 no
,以运行else
部分。如果它发现至少 yes
可以运行第一个条件。
答案 0 :(得分:1)
我认为您正在尝试从错误的角度解决问题。您必须先扫描集合,然后运行代码:
var mached = this.data.every(t => t.hhead == 'yes'); //this will print true
Object.keys(this.data).forEach(key => {
if (mached) {
console.log('Yes '+(this.data[key].hhead === 'yes'))
this.snackBar.open('This household already have ' + this.data[key].far + ' ' + this.data[key].lar + ' (id: ' + this.data[key].iid + ' ) as a head of household', 'Close', {
panelClass: 'error'
});
} else {
console.log('No '+(this.data[key].hhead === 'no'))
if (data['age'] <= 17 && data['age'] < this.maxAge && (selectedFr == "Head Of Household")) {
let message = 'This individual is not the oldest in his family to be the head of household. Do you want to complete this action ?';
this.openDialog(message, updateType, ind_id, newSts, newMs, newFr, newHH, oldHH, missingData);
}
}
});