The following simplified example works but not sure it's the most efficient approach because I'm calling getLocation() multiple times within a Svelte each block per iteration:
<script>
export let schedule = {
locations: [
{
_id: 1,
name: 'Boston',
parking: 'Onstreet'
},
{
_id: 2,
name: 'New York',
parking: 'Paid lot'
}
],
sections: [
{
locationId: 2,
day: 1
},
{
locationId: 1,
day: 2
}
]
}
function getLocation(id) {
return schedule.locations.find( ({ _id }) => _id === id )
}
</script>
<template>
{#each schedule.sections as section}
<p>{getLocation(section.locationId).name} {getLocation(section.locationId).parking}</p>
{/each}
</template>
Other approaches I could use:
- Populate a Map object with the locationId as the key and location object as the value and reference it in the each block. Was thinking it probably has more overhead since I have to build the map and then lookup the value by key each time anyway.
- Denormalize the data by adding location properties to the section objects before displaying. As I'm passing in the data, did not want to mutate it or have the overhead of cloning.
- This one is easy on the eyes but perhaps less efficient because of the iteration... create a one-element array with location object returned from getLocation() and use an inner each block to access the location properties like this...
<template>
{#each schedule.sections as section}
{#each [getLocation(section.locationId)] as location}
<p>{location.name} {location.parking}</p>
{/each}
{/each}
</template>
I'm new to Svelte. Any thoughts on what the most efficient approach would be? Was my first approach the best (or am I way off base)?