Skip to content
Advertisement

Update array elements

I am trying to do something similar to a shopping cart, where initially there is a series of products that I load with an array of objects.

JavaScript

I show the list of products with svelte like this:

JavaScript

And through the function addProduct() I update the array inventory with the product id and the number of units of that product

JavaScript

Where I don’t know how to set it up is in each product, where it now says { “0 products”}, update it dynamically as the user adds each of the products

Thanks a lot !

Advertisement

Answer

I understand with { "0 products"} you want to display the number of items in the inventory. You could do this by replacing it with

JavaScript

Optional chaining (?.) and Nullish coalescing operator (??) used

Besides the fact that you want to assign inventory to itself after you made an edit like pushing an item, so that a re-render is triggered, there’s a logical problem in addProduct(). If there’s already an element, you don’t want to push another one, but edit the existing, which gives

JavaScript

While this would work – see this REPL – I would consider making inventory an object instead of an array, because it was a bit ‘quicker’ to check for entries and edit them, compare this REPL (the entries could always be easily iterated using Object.entries/.keys/.values(inventory))

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement