英文:
Filtering array of objects in svelte typescript
问题
我想检查特定用户名是否在用户对象数组中。
我正在使用FastAPI获取选民列表。用户具有类似{"username": "mickey"}
的用户名值。我将当前用户存储在$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) }
然而,question.voter.username.forEach(v => v.username)
一直返回未定义。我有点困惑于Python和JavaScript的性质。
或者我的方法有问题吗?我应该创建另一个Fast API调用吗?
英文:
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
得分: 1
假设 $username
包含一个字符串值,可以进行如下检查:
{#if question.voter.some(v => v.username === $username)}
另一种可能的方式是:
{#if question.voter.map(v => v.username).includes($username)}
但我认为使用 .some()
更加高效,因为它只迭代数组一次并在找到结果后立即停止。
请注意,您在评论中提到的当前解决方案使用 String.prototype.includes 是容易出错的,因为它将匹配包含当前用户名的更长用户名。例如,当有一个用户对象 {username: 'foobar'}
和 $username = 'foo'
时,这将匹配,即使没有 {username: foo}
。可以调整为:
{#if question.voter.filter(v => v.username === $username).length == 1}
但与此相比,这不是首选选项。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论