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}
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With