Shopping cart... Total sum

I have this use case:
I am creating a shopping cart on weweb, I have been able to make the functionality and get to the check out process as shown in the first and second image,


I have a problem trying to add the total dynamically, I created an object type variable so that the product id and the selected quantity are saved dynamically, can anyone help me with ideas to know how I can do the total sum of all the products, thanks all

image

const cart = [
    {
        price: 120,
        amount: 1
    },
    {
        price: 120,
        amount: 1
    },
    {
        price: 120,
        amount: 1
    }
]

let total = 0;

for(const item of cart){
    total += (item.price * item.amount)
}

return total

Replate cart with your array that is formatted like the one in the code

Hey Luka, thanks for the help here. Im nott sure what im doing wrong in the JS code, i just share you waht i did but i dont have an answer

`const cart = variables[‘9af52da4-3ecf-40be-8f90-36b5befa89c9’];

let total = 0;

for (const item of cart) {
total += (item.price * item.amount);
}

console.log(total);
return total;
``

I think you should first of all use an array of objects (items), not an object. If you want to do it with your object though, you can use this one-liner formula. I would probably still opt for the array approach as also @luka suggested, as it is more flexible and simpler (no need to to the values() conversion).

values( [your_cart_object_here] ).reduce((partialSum, a) => partialSum + a, 0);

Thanks for the reply, i tried using an array, but im stuck in the same issue, the Total, how can i do the math (price*qty) an the total SUM, any thought?


image

[carrito_array_here].reduce((partialSum, item) => partialSum + item.qty*item.price, 0);