Angular 5 - Dynamically add items to an array

Viewed 323

I have these two functions:

cart() which is an array object (this information is static)

cartItems which is an array object (this information is dynamic)

Inside the cart there can be several cartItems. How do I push different items into this cart so my final result would look like this:

JSON:

"cart": [
            {
                "id": "1",
                "cartItem": [
                    {
                        "id": "cart Item 1",
                        "action": "New",
                        "quantity": 1,
                    },
                    {
                        "id": "cart Item 2",
                        "action": "New",
                        "quantity": 1,
                    }
            }
            ]

FUNCTIONS:

private cart(): CaCartItemsModel{
    return new CaCartItemsModel(
      "1",
      "Cambio",
      "TV"
);

private cartItems(): CaCartItemModel{
    return new CaCartItemModel(
      "cart Item 1/cart Item 2",
      "New",
      1
    );
  }
1 Answers

I managed to resolve what I needed in the following way:

private createCartItems(cancellationModel: CancellationModel) {

    this.request.caAcProductOrderModel.caCartItems.getAllCartItems()
      .push(this.setCartItems());

    cancellationModel.channels.forEach(channel => {
      this.request.caAcProductOrderModel.caCartItems.getAllCartItems()
        .forEach(caCartItem => {
          caCartItem.caCartItem.getAllCartItem()
            .push(this.setCaCartItemModel(
              channel.id,
              channel.action,
              channel.name,
              "",
              true
            ));

          caCartItem.caCartItem.getAllCartItem()
            .forEach(cartItem => {
              cartItem.caProduct.caProductRelationship.getAllCaProductRelationship()
                .push(this.setCaProductRelationshipModel(channel.type));
              cartItem.caProductOffering.caCategory.getAllCategories()
                .push(this.setCaCategoryModel("promo"));
              cartItem.caProductOffering.caAttributes.getAllAttributes()
                .push(this.setCaAttributesModel("Numero fijo Asociado", this.activeCustomerServiceProvider.getPhoneNumber()));
              cartItem.cartItemRelationship.getAllCartItemRelationship()
                .push(this.setCaCartItemRelationshipModel(channel.id, "reliesOn"));
            });
        });
    });
}
Related