我有这段代码,可以过滤我的数据。我问我,如果有办法不明确地过滤每个字段(id
,mandant
,zonenlogik
...)。
也许有一种更流畅的方法可以在所有字段上设置过滤器而无需显式调用它们?
let filteredList = this.state.freights.filter((freight) => {
if (freight.id.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
return freight;
}
if (freight.mandant.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
return freight;
}
if (freight.zonenlogik.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
return freight;
}
if (freight.frachtart_nr.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
return freight;
}
if (freight.transportart_nr.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
return freight;
}
if (freight.spedit_nr.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
return freight;
}
if (freight.spedit2_nr.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
return freight;
}
if (freight.lager_nr.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) {
return freight;
}
});
答案 0 :(得分:2)
您可以使用Object.values()
获取对象值,然后循环遍历这些值以检查字符串中是否存在子字符串,然后返回已过滤的对象
let filteredList = this.state.freights.filter((freight) => {
let search = this.state.search.toLowerCase();
var values = Object.values(freight);
var flag = false
values.forEach((val) => {
if(val.toLoweCase().indexOf(search) > -1) {
flag = true;
return;
}
}
if(flag) return freight
});
答案 1 :(得分:1)
我假设你想要另一个代码,它可以获得与你发布的代码相同的结果。这是我的:
const searchTerm = this.state.search.toLowerCase();
let filteredList = this.state.freights.filter((freight) => {
// get all keys of freight
const keys = Object.keys(freight).map(k => k.toLowerCase());
for (let k of keys) {
// if key (e.g id) matches the search term, return freight
if (k.indexOf(searchTerm) !== 1) {
return true; // we want this freight object
}
}
return false;
});

答案 2 :(得分:0)
这是es5单线(某种):
let filteredList = this.state.freights.filter(freight =>
Object.keys(freight).some(
key =>
freight[key]
.toLowerCase()
.indexOf(this.state.search.toLowerCase()) !== -1,
),
);