How to print both Object key and value with Each block in Svelte?

Viewed 8462

I wanted to loop through the sections object and print out the key in h1 and the value in p tag. I'm fine with enclosing this in an array.

<script>
    const sections = 
    {"Title 1": "paragraph",
    "Title 2": "paragraph",
    "Title 3": "paragraph",
    "Title 4": "paragraph",
    "Title 5": "paragraph"}
</script>
    
{#each sections as section}
    <h1>{title}</h1>
    <p>{paragraph}</p>
{/each}

1 Answers

you have an Object with multiple keys each with their values.

you need to convert the object into an array first then iterate over it

<script>
    const sections = {
        "Title 1": "paragraph",
        "Title 2": "paragraph",
        "Title 3": "paragraph",
        "Title 4": "paragraph",
        "Title 5": "paragraph"
    }
    // Object.entries() converts an Object into an array of arrays, 
    // each sub array first index is the a key and the second index is a value
    // Object.entries({key: value, key:value}) => [[key, value], [key,value]]
</script>

{#each Object.entries(sections) as [title, paragraph]}
    <h1>{title}</h1>
    <p>{paragraph}</p>
{/each}

here is a repl

Related