简体   繁体   中英

Svelte iterate over array of objects

Having this fixed array of objects like this:

export let items = [
  {
    name: 'package',
    subname: 'test'
  },
  {
    name: 'package',
    subname: 'test1'
  },
  {
    name: 'pack',
    subname: 'test2'
  }
]

it is possible to use iterate using each or anything else to get something like this?

<div class='item'>
  <div class='name'>package</span>
  <div class='subname'>test</span>
  <div class='subname'>test1</span>
</div>

<div class='item'>
  <div class='name'>pack</span>
  <div class='subname'>test2</span>
</div>

A solution would be to merge the items together in an object that has for keys the different name s and as value an array of all subname s just like that:

{
    "package": [
        "test",
        "test1"
    ],
    "pack": [
        "test2"
    ]
}

You can do that in a getSubnamesByName function:

    const getSubnamesByName = (items) => {
        const mergedItems = {}
        items.forEach(({name, subname}) => {
            if (mergedItems[name]) mergedItems[name].push(subname)
            else mergedItems[name] = [subname]
        })
        
        return mergedItems
    }

Then just store the result in a mergedItems variable that is populated when the component is mounted:

<script>
    import { onMount } from 'svelte';

    const ITEMS = [ /* ... */ ];
    
    let mergedItems = {}
    
    const getSubnamesByName = (items) => { /* ... */}
    
    onMount(async () => {
        mergedItems = getSubnamesByName(ITEMS)
    })
</script>

And finally iterate on this object keys and values by using 2 #each blocks:

{#each Object.keys(mergedItems) as name}
    <div class='item'>
        <div class='name'>{name}</div>
        
        {#each mergedItems[name] as subname}
            <div class='subname'>{subname}</div>
        {/each}
    </div>
{/each}

Have a look at the REPL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM