Home > Blockchain >  How to iterate over a json dictionary in Svelte
How to iterate over a json dictionary in Svelte

Time:10-30

In Svelte, the #each construct can be used to iterate over an array-like object. If one has a JSON dictionary object instead, does Svelte provide a way to iterate over the JSON dictionary in order to populate a dropdown menu? My data is the result of an API call and looks like:

{ “foo”: “bar”, “batz”: “boink” }

CodePudding user response:

You first convert your object to an array with the infos (keys/values/boths) you would like to display.
This array is then iterable with an #each loop. See this REPL

<script>
const obj = { foo: "bar", batz: "boink" }

let keys = Object.keys(obj)  // ["foo", "batz"]
let values = Object.values(obj)  // ["bar", "boink"]
let entries = Object.entries(obj)  // [["foo", "bar"], ["batz", "boink"]]

</script>

{#each entries as [key, value]}
    <div>
    {key} - {value} 
    </div>  
{/each}

  • Related