我有一个过滤器函数,它使用 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)
});
});
关于javascript - 使用 array.filter 向下多个级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47823734/