Lists & Keys
When manipulating lists, it's good practice to add an key (identifier), when you loop through that list with #each
. This will help Svelte identity the item in the list, and avoid issues.
{#each [name-array] as [item-array], [index-key] (item-array.key)}
<p>{index}</p>
<p>{item.id}</p>
<p>{item.name}</p>
{/each}
---
<script>
let sampleArray = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Doe' },
{ id: 3, name: 'John Smith' },
{ id: 4, name: 'Jane Smith' },
{ id: 5, name: 'John Brown' },
];
</script>
<main>
{#each sampleArray as item, index (item.id)}
<p>{index}</p>
<p>{item.id}</p>
<p>{item.name}</p>
{/each}
</main>
Last updated