Search code examples
javascripthtmlsveltesveltekitsvelte-component

Svelte: How to bind to a defined object inside an array


Here's the code:

<script>
let array = [
    {id: 1, first: "x"},
    {id: 2, second: "y"}
];
</script>

<input type="text" bind:value={array.first}/>

Now if you change the value inside the input and look at the value of array.first, it will be correct.

However, if you look at the whole array object (i.e. console.log(array)) it will not be updated and instead will show you the original values it was initiated with.

Further to this, when putting a nested object in:

let array = [
    {id: 1, first: [{id: 1, value: "x"}]},
    {id: 2, second: [{id: 1, value: "y"}]}
];

Results in an undefined error from Svelte when binding to array.first.value. However, when not binding to it and only interacting with it through JS, the value is accessible and defined.

What am I not doing right here? Or is it not possible to bind to nested objects in arrays? Or even non-nested.

Thanks!


Solution

  • You need to make sure that you bind to the first property of the element at index 0 in the array, not the first property of the array itself.

    This will also work for the nested example array[0].first[0].value in your question.

    Example (REPL)

    <script>
        let array = [
            { id: 1, first: "x" },
            { id: 2, second: "y" }
        ];
        
        $: console.log(array);
    </script>
    
    <input type="text" bind:value={array[0].first}/>