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
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 useusername
directly, sample code below:Your current solution means you are trying to match a username that is exactly
"${username}"
, which means you have to have following in yourusers
for it to match:With your approach, the type of
user
is going to be a string, and therefore you’re recieving youruser
s as a JSON parsed in a String format. As follows: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.
Using a classic implementation of this, making sure that the user exists before accessing the user, you may do the following:
At the end of both approachs you have the user variable as following: