按数组内的对象键过滤

时间:2018-07-16 02:46:10

标签: javascript

使用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); 

2 个答案:

答案 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())