skip to Main Content

I want to filter my users array by "username" variable from js.

Server side:

var users = data.filter(u => u.id.startsWith('user_')).map(u => u.value);
// [{"username": "arin2115", "someotherdata": "someotherdata"}, {"username": "tesla", "someotherdata": "someotherdata"}]

return res.render('admin/users', {users: users});

Client side:

<script>
  var someelement = document.getElementById("someelement");

  var username = "arin2115";

  var user = `<%-JSON.stringify(users.filter(x => x.username == "${username}")[0])%>`;

  someelement.innerHTML = user.someotherdata;
</script>

like something above, I have tried many ways to do it but any of them doesn’t work.

Working solution from @AngYC:

var username = "arin2115";

var users = <%-JSON.stringify(users)%>;

var user = users.find(x => x.username == username);

Thanks.

2

Answers


  1. When you open the <%- bracket, it means you are in a JavaScript context. You don’t have to quote it again with "${username}" but rather use username directly, sample code below:

    var user = `<%-JSON.stringify(users.filter(x => x.username == username)[0])%>`;
    

    Your current solution means you are trying to match a username that is exactly "${username}", which means you have to have following in your users for it to match:

    [{ "username": ""${username}"" }]
    
    Login or Signup to reply.
  2. With your approach, the type of user is going to be a string, and therefore you’re recieving your users as a JSON parsed in a String format. As follows:

    var user = '[{"username":"x"}]';
    

    I believe you are looking for a single user, and get the object itself, not a string representation of it.

    So you may use this approach for ES2020 using optional chaining, please not that you might need polyfills for older browsers.

    var user = `<%- users.filter(x => x.username == "${username}")?.[0] %>`;
    

    Using a classic implementation of this, making sure that the user exists before accessing the user, you may do the following:

    var user = `<%- users.filter(x => x.username == "${username}") %>`; 
    if(user.length > 0) user = user[0];
    

    At the end of both approachs you have the user variable as following:

    var user = { username: "x" }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search