I have a dropdown that works well with simple values, but I just tried using arrays as values and now the initial dropdown-entry is empty.
I have created a REPL to illustrate the problem. As you can see I have also tried using selected=... to automatically select the first entry, but it doesn't work.
The only thing I can think of is to introduce another property to go back to simple values and then extract the array by filtering the original array, but it seems rather cumbersome. I wonder if there is another, more elegant, way that I'm missing.
Thank you in advance!
Edit: Here the code example as suggested:
<script>
const availableFilters = [
{ key: ['filterAll'], display: 'All Columns' },
{ key: ['name1', 'name2' ], display: 'Entry Names' },
{ key: ['ID1', 'ID2' ], display: 'Entry IDs' },
{ key: ['name1'], display: 'Entry 1 Name' },
{ key: ['ID1'], display: 'Entry 1 ID' },
{ key: ['name2'], display: 'Entry 2 Name' },
{ key: ['ID2'], display: 'Entry 2 ID' },
];
const simpleAvailableFilters = [
{ key: 'filterAll', display: 'All Columns' },
{ key: 'name1', display: 'Entry 1 Name' },
{ key: 'ID1', display: 'Entry 1 ID' },
{ key: 'name2', display: 'Entry 2 Name' },
{ key: 'ID2', display: 'Entry 2 ID' },
];
let currentFilter = { key: ['filterAll'], value: "", code: 0 };
let simpleCurrentFilter = { key: 'filterAll', value: "", code: 0 };
</script>
Dropdown with array values:
<select bind:value={currentFilter.key}>
{#each availableFilters as filter, i}
<option selected={i === 0 ? 'selected' : ''} value={filter.key}>{filter.display} - {i}</option>
{/each}
</select>
<span>
Selected key: {currentFilter.key}
</span>
<br/>
Simple Dropdown:
<select bind:value={simpleCurrentFilter.key}>
{#each simpleAvailableFilters as filter, i}
<option value={filter.key}>{filter.display} - {i}</option>
{/each}
</select>
<span>
Selected key: {simpleCurrentFilter.key}
</span>
Try this:
let currentFilter = availableFilters[0].key;
and you can remove selected={i === 0 ? 'selected' : ''} from the option.
Simply replace
let currentFilter = { key: ['filterAll'], value: "", code: 0 };
by
let currentFilter = availableFilters[0];
Even though the object has the exact same structure, it's still a different object that the one on the first position in the array. {} === {} // false The same applies to arrays.
['filterAll'] === ['filterAll'] // false
'filterAll' === 'filterAll' // true
currentFilter would have then this structure
{key: *bindedValue*, display: 'All Columns'}
If you want to extract the array you have to access the key when setting the initial value
let currentFilter = availableFilters[0].key;
and change the binding on the option
<select bind:value={currentFilter}>
REPL A Repl is great to have, but it would be better to include the code as well, in case the Repl might break...