我有一个过滤功能,它使用filter
快速搜索数组中的文本:
filtered = filtered.filter((row) => {
return Object.keys(row).some((key) => {
return String(row[key]).toLowerCase().indexOf(this.quickSearch.toLowerCase()) > -1
})
})
这对于单级数组非常有用,但不确定如何使其适应未知数量的对象数组级别,如下所示
{
'name': 'james',
'post': {
'name': 'my favorite teams'
}
}
上面的代码发现james
,没问题,但是不会找到teams
因为它还不够深入。
当然,我不想硬编码类似的东西if row[key] == 'post'
,因为我将此代码用于多个数据源并且需要它是动态的。
我如何适应它以在多层数组中工作,如上面的示例?
如果层次很多,那么递归是最好的解决方案:
let searchString = this.quickSearch.toLowerCase(); // do this only once instead of calling toLowerCase over and over again, besides we are using a regular function (not an arrow one) so "this" will be messed up anyways
filtered = filtered.filter(function search(row) { // name the function so we can use recursion (thus we can't use an arrow function)
return Object.keys(row).some((key) => { // ...
if(typeof row[key] === "string") { // if the current property is a string
return row[key].toLowerCase().indexOf(searchString) > -1; // then check if it contains the search string
} else if(row[key] && typeof row[key] === "object") { // oterwise, if it's an object
return search(row[key]); // do a recursive check
}
return false; // return false for any other type (not really necessary as undefined will be returned implicitly)
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)