2017-03-28 117 views
1

是否有一種方法不區分大小寫過濾lodash?我試過這個(見下文),但這只是部分工作(當用戶輸入也是小寫)。另一個問題是在一次搜索後,所有字符都是小寫。Lodash過濾忽略案例

我想過濾不管如何(小寫或大寫)。

filter(q: string) { 
    let query = q.trim(); 
    let searchData = []; 
    searchData = clone(this.data); 

    searchData = searchData.map((entity) => { 
     entity.email = entity.email.toLowerCase(); 
     return entity; 
    }); 

    if (query) { 
     this.approverEntities = filter(searchData, (a) => a.email.indexOf(query) >= 0); 
    } else { 
     this.approverEntities = this.data; 
    } 
} 

在此先感謝!

回答

1

您可以使用filter()method(),並且不區分大小寫的正則表達式:

_.filter(searchData, _.method('email.match', /foo/i)); 

或者,如果搜索詞是動態的:

const filterCaseInsensitive = (search, searchData) => 
    _.filter(searchData, _.method('email.match', new RegExp(search, 'i')); 
1

這種方法制定出非常適合我:

this.approverEntities = _.filter(searchData, (a) => {return new RegExp(a.email, 'i').test(query)}); 

一個注意事項是,如果a.email包含任何特殊字符,正則表達式會將其作爲正則表達式標記處理(例如)。括號,括號等)。該解決方案將處理特殊字符,無論...

this.approverEntities = _.filter(searchData, (a) => {return a.email.toLowerCase() == query.toLowerCase()}); 
1

這是我如何做一個區分大小寫的過濾器,同時還僅需要一個子:

this.approverEntities = filter(searchData, function(a){ 
    return a.email.toLowerCase().indexOf((query).toLowerCase()) !== -1; 
}