1

I'm searching in svelte documentation about this, but I can't get it.

What I want is to show only 4 objects from an array

For example:

let data = [
    {id:1, name: 'John'},
    {id:2, name: 'Peter'},
    {id:3, name: 'Stev'},
    {id:4, name: 'Clar'},
    {id:5, name: 'Eyad'},
    {id:6, name: 'Vector'}
]

Then the results only show

John
Peter
Stev
Clar

Seems like ReactJS as you just add index in map() function.

0

2 Answers 2

4

The each block allows you to iterate over an array and gives you two variables: the current element as its index in the array. You can combine this with an if block to check if the index is within the range you'd like:

Svelte REPL Link

<script>
    let data = [
    {id:1, name: 'John'},
    {id:2, name: 'Peter'},
    {id:3, name: 'Stev'},
    {id:4, name: 'Clar'},
    {id:5, name: 'Eyad'},
    {id:6, name: 'Vector'}
];
</script>

{#each data as person, index}
    {#if index < 4}
        <p>
            {person.name}
        </p>
    {/if}
{/each}

Alternatively, you could first use .splice() first and forgo the if block:

Svelte REPL link

<script>
    let data = [
    {id:1, name: 'John'},
    {id:2, name: 'Peter'},
    {id:3, name: 'Stev'},
    {id:4, name: 'Clar'},
    {id:5, name: 'Eyad'},
    {id:6, name: 'Vector'}
];
</script>

{#each data.slice(0, 4) as person}
    <p>
        {person.name}
    </p>
{/each}
3

You can just apply a .slice(), either in the template in {#each} or just directly in the script. You can use any valid JS in the script block.

{#each data.slice(0, 4) as ...}
let data = [/* ... */].slice(0, 4)

If the data can change and you always want the first four elements, you can use a reactive statement:

$: slicedData = data.slice(0, 4)

Note that if the elements can change in ways other than just appending elements, an {#each} over the array should also use a key (see docs).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.