【问题标题】:Show product.length when I have JSON / OBJ / JSON / OBJ / JSON当我有 JSON / OBJ / JSON / OBJ / JSON 时显示 product.length
【发布时间】:2020-03-29 02:37:32
【问题描述】:

我有这个 JSON

{
    "StatusCode": 0,
    "StatusMessage": "OK",
    "StatusDescription": [
        {
            "_id": "12123",
            "dateCreated": "2019-12-03T13:45:30.418Z",
            "pharmacy_id": "011E752345553380ABC13FFA163ECD15"
            "products": [
                {
                    "productID": "1",
                    "quantity": 3,
                    "product_name": "BETADINE",
                    "price": 10
                },
                {
                    "productID": "2",
                    "quantity": 1,
                    "product_name": "EUCARBON",
                    "price": 10
                }
            ]
        },
        {
            "_id": "56233",
            "dateCreated": "2019-12-04T09:55:21.555Z",
            "pharmacy_id": "011E762345552280FBC13FFA163ECD10"
            "products": [
                {
                    "productID": "44",
                    "quantity": 1,
                    "product_name": "BETADINE",
                    "price": 10
                }
            ]
        }
    ]
}

在这个 JOSN 中,我想获取产品的长度。例如,我有 2 家药店和 5 种产品。我想在我的购物车中显示 5。

所以我用这个函数从 API 得到这个 JSON:

  public cart: Shop[];
  cartlength: number;

  ngOnInit(): void {
        this.shopservice.getShoppingCart().subscribe(
            cart => {
                this.cart = cart;
                this.cartlength = cart.length;
            },
            err => console.error('errorrrrrrr', err),
            () => console.log('error')
        );
    }

在 HTML 中:

<ActionItem ios.systemIcon="9" ios.position="left" android.position="actionBar"  [text]='cartlength'></ActionItem> 

有什么想法吗?

【问题讨论】:

  • 您是否收到任何错误信息?
  • 没有。在this.cartlength = cart.length; 我得到第 2 名。但我想得到产品的数量。
  • 如果您希望所有产品的总长度只需使用 forEach 循环,只需使用 cart.StatusDescription[0].products.length 即可获取第一个产品的长度。

标签: json angular typescript object nativescript


【解决方案1】:

如果购物车是包含所有药房的数组,您可以使用 reduce 方法来确定每个药房所有产品的总量。

this.cartlength = this.cart.reduce((count, pharmacy) => {
    count += pharmacy.products.reduce((totalQty, product) => {
        return totalQty += product.quantity;
    }, 0)
    return count;
}, 0)

【讨论】:

  • 没错,在这种情况下,他可以对每个药房中的产品数组使用另一个减少,相应地编辑答案。
猜你喜欢
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多