Search code examples
javascriptpayload

Cart data aggregation in javascript


I need to write a data aggregation method for my cart, but i'm stuck. I have const payload with empty array and loop that will run getData() method for every product in my cart and push the result to my empty array. Also i need my getData() method, that will return for me id, amount, price and priceSingel. All of those we got in CarProduct constructor. I am still new and i do get stuck sometimes with the basics.

const payload = {
        products: [],
        address: 'test',
        totalPrice: thisCart.totalPrice,
      };

      for(let product of thisCart.products) {
        product.getData();
      }
      payload.products.push(product);
  /* get data for .getData */
    getData() {
      return id;
      return amount;
      return price;
      return priceSingle;
      return params;
    }
/* part of cart product constructor */
class CartProduct {
    constructor (menuProduct, element) {
      const thisCartProduct = this;

      thisCartProduct.id = menuProduct.id;
      thisCartProduct.name = menuProduct.name;
      thisCartProduct.price = menuProduct.price;
      thisCartProduct.priceSingle =menuProduct.priceSingle;
      thisCartProduct.amount = menuProduct.amount;

Solution

  • Hard to help you with this little view of your code.

    However, some problems that you can resolve:

    A method can't have more than ONE effective return, the first encountered is used. So for your getData(), you should return an object:

    getData() {
      return { // this is a shortcut where key is named like the variable
        id,
        amount,
        price,
        priceSingle,
        params
      }
    }
    

    I don't know what's your params here.

    Secondly, add data to your array while you loop, not after (and here you don't use the getData() return)

    for(let product of thisCart.products) {
      payload.products.push(product.getData());
    }