简体   繁体   中英

JavaScript search by object attribute

I have the following method used to search from a list of users by the username attribute. My confusion is that line 6 console.log("Users filtered " + JSON.stringify(user)); displays to console the object that matches the username that I am typing in search bar. It kind of works but only for first element. For example, I have two users vicky, valentine and when I search by v I get only:

Users filtered {"age":"21","username":"vicky","lastUpdated":{"seconds":1601845200,"nanoseconds":0}}

And I get the error which points to line:
return userObject.username.toLowerCase().includes(searchString); :

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
    at users.js:46
    at Array.filter (<anonymous>)
    at 

which makes me think that there must be something wrong with userObject.username attribute but I do not get why since it is a simple JSON object and I just want to get the username value. What am I doing wrong?

searchBar.addEventListener("keyup", (e) => {
  let searchString = e.target.value.toLowerCase();
  let filteredUsers = usersArray.filter(user => {
    let userObject = {};
    userObject = JSON.stringify(user);
    console.log("Users filtered " + JSON.stringify(user));
    return userObject.username.toLowerCase().includes(searchString);
  });
  console.log("Users filtered " + filteredUsers);
  removeUsers();
  filteredUsers.forEach((user) => {
    createUser(user);
  });
});

The issue is with this:

userObject = JSON.stringify(user);

JSON.stringify() as the name implies, returns a string which wouldn't have a username property.

Try simplifying your filter to this:

let filteredUsers = usersArray.filter(user => {
    return user.username.toLowerCase().includes(searchString);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM