Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

svelte

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}

like image 632
rohanharikr Avatar asked Nov 19 '20 10:11

rohanharikr


People also ask

How do you iterate keys in an object?

You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.

How do you find the array of keys in an object?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.


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

like image 59
OmG3r Avatar answered Oct 21 '22 10:10

OmG3r