Angular 7和对象搜索如何查找严格值

时间:2018-12-07 13:36:38

标签: arrays angular object angular7

我正在从服务器返回的对象的字段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);
    }
    }
});

此脚本的问题在于ifelse都是正确的。因此,两个脚本都将运行。

原因是,在第一个条件下,一旦找到yes值,条件就变为true。

第二个,一旦找到no,它将运行。

数组类似于:

enter image description here

所以我需要的是如果一个数组在所有行中仅包含 no,以运行else部分。如果它发现至少 yes可以运行第一个条件。

1 个答案:

答案 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);
    }
    }
});