Search code examples
javascriptnode.jsexpressvariablesejs

Using JS variables when filtering an array from EJS?


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.


Solution

  • 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}\"" }]