I want to check whether a certain username is in the array of user objects.
I am fetching voter list with fastapi. A user has username value like {"username": "mickey"}. I am storing the current user with persistent_storage as $username.
<script>
let question = {answers:[], voter:[], content: ''}
function get_question() {
fastapi("get", "/api/question/detail/" + question_id, {}, (json) => {
question = json
})}
</script>
{#if question.voter.forEach(v => v.username).includes($username) }
However, question.voter.username.forEach(v => v.username) keeps returning undefined.
I am kinda confused between the nature of python and javascript.
Or is my approach wrong? Should I create another fast API call?
Assuming
$usernameholds a string value the check could beAlso possible would be
but I think
.some()is besides being shorter also more efficient because it only iterates the array once and stops as soon as a result is foundNotice that your current solution mentioned in the comments using String.prototype.includes
is error prone because this will match longer usernames containing the current username. Like when there's a user object
{username: 'foobar'}and$username = 'foo'this will match when there's no{username: foo}. Could be adjusted tobut compared that's not the preferred option