javascript / beginner
Snippet
Iterating Object Entries with Arrays in Svelte Each Blocks
In Svelte, the `{#each}` block natively loops over iterable array structures. When working with JavaScript objects, `Object.entries()` transforms key-value pairs into an array of `[key, value]` tuples, enabling clean array destructuring directly inside the template loop.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
<script>let userProfile = { name: "Alex", role: "Developer", level: "Beginner" };</script><dl>{#each Object.entries(userProfile) as [key, value]}<dt>{key}:</dt><dd>{value}</dd>{/each}</dl>
svelte
Breakdown
1
let userProfile = { name: "Alex", role: "Developer", level: "Beginner" };
Declares a JavaScript object containing key-value pairs representing user profile data.
2
{#each Object.entries(userProfile) as [key, value]}
Converts the object into an array of key-value pairs and unpacks each pair using array destructuring syntax.
3
<dt>{key}:</dt>
Renders the extracted key name inside an HTML definition term tag.
4
<dd>{value}</dd>
Renders the extracted value associated with the key inside an HTML definition description tag.
5
{/each}
Closes the Svelte iteration block once all entries in the array have been processed.