Iterate Over Each Array Item in Svelte
- 1 minute read
Svelte has a useful logic block called the each block that we can use for iterating over array items in our markup:
<script>
let shapes = [`Circle`, `Square`, `Triangle`];
</script>
<ul>
{#each shapes as shape}
<li>{shape}</li>
{/each}
</ul>
You can also get the index, i
, of the loop:
<ul>
{#each shapes as shape, i}
<li>{i} {shape}</li>
{/each}
</ul>
The index is a counter that starts from 0 and increments once for each item in the array.
Better object array iteration
If you have an array of objects, you can access the individual values like this:
<script>
let shapes = [
{
color: `Red`,
shape: `Circle`,
},
{
color: `Blue`,
shape: `Square`,
},
{
color: `Yellow`,
shape: `Triangle`,
}
];
</script>
<ul>
{#each shapes as shape}
<li>{shape.color} {shape.shape}</li>
{/each}
</ul>
Conclusion
The each
block is extremely powerful and it is absolutely essential to writing concise, readable, and efficient Svelte components.
I hope you enjoyed this quick tutorial!