对象数组上的Match()



我有一个包含多个变量的对象数组。

let Books = [];
class Book {
constructor(docID, title, author, edition, publication, year) {
this.docID = docID;
this.title = title;
this.author = author;
this.publication = publication;
this.year = year;
this.edition = edition;
}
}
//Example
ISBN = "978-1-56619-909-4";
title = "Book title";
authors = ["author1", "author2"];
edition = 1;
publication = "Book publisher";
year = 2021;
temp = new Book(ISBN, title, authors, edition, publication, year);
Books.push(temp);

我有一个搜索栏,我需要搜索和过滤数组中的某些变量。例如,我需要在title变量中搜索匹配项,并只筛选那些与输入匹配的项。我使用match((来查找匹配项。

let searchText = "title"; //Given by user
if (searchText != "") {
let searchQuery = new RegExp(searchText, 'i');
filtered_results = Books.match(searchQuery);
} else {
filtered_results = Books;
}

然而,我收到一个错误,说match((不适用于Books(因为它不是字符串(。如果我在字符串变量上使用它,它就会起作用(Books[1].title.match(((。在这种情况下,我需要使用一个循环,并在每次迭代中寻找匹配项。

有没有一种没有循环的有效方法?因为如果标题不匹配,我需要检查作者和出版物中的匹配项。我不认为每次都循环遍历对象是一种有效的方法。

您应该使用Array.prototype.filter

要过滤你的一系列书籍,

let searchQuery = new RegExp(searchText, 'i');
filtered_results = Books.filter(book => searchQuery.test(book.title));

在这里,我们检查Books数组中的每本书,然后使用RegExp.test,如果书名是匹配的

您也不需要if条件,如果是空字符串,RegExp将返回所有书籍。

最新更新