我尝试合并一个返回与标题匹配的数组的搜索函数。现在,它只返回完全匹配。我想要类似于this filter table function的东西,无论何时我输入一个字母,结果都会缩小。以下是我正在使用的内容以及我的数据。
let movies = [
{title: "Pacific Rim", year: "2018"},
{title: "Batman", year:"1984"},
{title: "Super Troopers 2", year: "2018"}
]
let filteredMovies = movies.filter(movie => {
if (this.state.query.length === 0) {
return movie;
} else {
return movie.title === this.state.query;
}
});
我应该使用.filter
吗?也许某种正则表达式?
感谢您的帮助
答案 0 :(得分:2)
使用String.includes()
查找包含字符串的所有标题:
const movies = [{"title":"Pacific Rim","year":"2018"},{"title":"Batman","year":"1984"},{"title":"Super Troopers 2","year":"2018"}];
const query = 'roop';
// if query length is 0 use a copy of movies, else get the filtered result
const filteredMovies = query.length ? movies.filter(movie => {
return movie.title.includes(query);
}) : [...movies];
console.log(filteredMovies);

答案 1 :(得分:0)
如果你想测试忽略大小写,那么你可以使用正则表达式
(new RegExp(this.state.query,"i")).test(movie.title)