Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading