[英]Svelte iterate over array of keys and get key from object
我有一個對象comments
:
let comments = {"id1": ..., "id2: ..., ...};
然后我有一個數組commentsSortedByDate
:
let commentsSortedByDate = ["id2", "id1", ...];
我想重復這些評論。 這是我嘗試過的:
{#each commentsSortedByDate as commentId}
<script> let comment = comments[commentId]; </script>
<div class="comment" class:new={comment.isNew}> ... </div>
{/each}
這不起作用。 我如何在循環中定義這個comment
變量,以便我可以多次訪問它而不必每次都輸入comments[commentId]
?
現在,除了您提出的建議( each
hack 或總是做comments[commentId]
)之外,沒有其他辦法可以做到這一點。 Svelte 有一個即將到來的新功能,這將使這成為可能: 在標記中使用 @const 。 這還沒有實現,但是當它實現時,你可以這樣做:
{#each commentsSortedByDate as commentId}
{@const comment = comments[commentId]}
<div class="comment" class:new={comment.isNew}> ... </div>
{/each}
或者您可以簡單地動態重新映射您的輸入數組並迭代comment
對象而不是 id:
{#each commentsSortedByDate.map(id => comments[id]) as comment}
<div class="comment" class:new={comment.isNew}> ... </div>
{/each}
我想出了一個駭人聽聞的解決方案,但我不會接受這是一個正確的答案。
{#each commentsSortedByDate as commentId}
{#each [comments[commentId]] as comment}
<div class="comment" class:new={comment.isNew}> ... </div>
{/each}
{/each}
您是否正在尋找這樣做這樣?
<script>
let commentsSortedByDate = ["id2", "id1"];
let comments = {
id1: {
text: "lorem",
},
id2: {
text: "ipsum",
},
};
</script>
<h2>
Comments
</h2>
{#each commentsSortedByDate as comment}
<ul>
<li>
{comment}: {Object.values(comments[comment])}
</li>
</ul>
{/each}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.