使用MDN (in the 'Searching in array' example half way down that page)中提供的示例,如何更改它以能够通过对象键对数组内的对象进行过滤?现在出现错误:TypeError: el.toLowerCase is not a function
。
var searchTerm = "lotty";
var arr = [
{user: "William", message:"meet me in the nanoscale library"},
{user: "Lotty", message:"sounds like a plan"}
];
function filterItems(query) {
return arr.filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
})
}
var filteredArr = filterItems(searchTerm);
console.log(filteredArr);
答案 0 :(得分:2)
el
是要迭代的对象,而不是user
字符串,因此el.toLowerCase()
不起作用。根据需要,首先将el
分解为user
:
var newUser = "lotty";
var arr = [
{user: "William", message:"meet me in the nanoscale library"},
{user: "Lotty", message:"sounds like a plan"}
];
function filterItems(query) {
return arr.filter(function({ user }) {
return user.toLowerCase().indexOf(query.toLowerCase()) > -1;
})
}
var filteredArr = filterItems(newUser);
console.log(filteredArr);
或更简洁地说,使用现代语法和.includes
:
var newUser = "lotty";
var arr = [
{user: "William", message:"meet me in the nanoscale library"},
{user: "Lotty", message:"sounds like a plan"}
];
const filterItems = query => arr.filter(
({ user }) => user.toLowerCase().includes(query.toLowerCase())
);
var filteredArr = filterItems(newUser);
console.log(filteredArr);
答案 1 :(得分:1)
CertainPerformance的答案非常好。但是,如果要使用分解,则必须确保该对象具有user
键。像这样:user&&user.toLowerCase().includes(query.toLowerCase())