使用array.filter向下多个级别 [英] Using array.filter down multiple levels
问题描述
我有一个过滤器功能,它使用filter
快速搜索数组中的文本:
I have a filter function, which uses filter
to quickly search a text in an array:
filtered = filtered.filter((row) => {
return Object.keys(row).some((key) => {
return String(row[key]).toLowerCase().indexOf(this.quickSearch.toLowerCase()) > -1
})
})
这对于单级数组非常有用,但是不确定如何适应这种情况以降低未知数量的对象数组级别,例如
This works great for single level array, but not sure how to adapt it to work down unknown number of levels of array of objects like this
{
'name': 'james',
'post': {
'name': 'my favorite teams'
}
}
上面的代码可以找到james
,没问题,但是由于teams
的深度不够,所以找不到teams
.
The code above finds james
, no problem, but it will not find teams
as its not going deep enough.
自然,我不想对if row[key] == 'post'
之类的东西进行硬编码,因为我正在将此代码用于多个数据源,并且需要动态代码.
Naturally I don't want to hardcode something like if row[key] == 'post'
, because I'm using this code for multiple data sources and need it to be dynamic.
我如何适应以上示例中的多级数组?
How do I adapt this to work in multi level arrays like the example above?
推荐答案
如果级别很多,则递归是最佳解决方案:
If there are many levels, then recursion is the best solution:
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)
});
});
这篇关于使用array.filter向下多个级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!