Filtering array of objects in svelte typescript

316 Views Asked by At

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?

1

There are 1 best solutions below

3
Corrl On

Assuming $username holds a string value the check could be

{#if question.voter.some(v => v.username === $username)}

Also possible would be

{#if question.voter.map(v => v.username).includes($username)}

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 found

Notice that your current solution mentioned in the comments using String.prototype.includes

{#if question.voter.filter(v => v.username.includes($username)).length == 1}

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 to

{#if question.voter.filter(v => v.username === $username).length == 1}

but compared that's not the preferred option