如何在 Svelte 中使用每个块打印对象键和值?

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

我想遍历 sections 对象并打印出 h1 中的键和 p 标签中的值。我可以将其封装在一个数组中。

<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}

您有一个包含多个键的对象,每个键都有它们的值。

您需要先将对象转换为数组,然后对其进行迭代

<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}

这是一个repl