【问题标题】:How to loop an array from JSON API如何从 JSON API 循环数组
【发布时间】:2018-02-25 00:08:09
【问题描述】:

我想从 Angular2 中的 JSON API 循环数组,但我不知道怎么做?

我想获得小计的总金额。希望你们能帮助我。提前谢谢你。

【问题讨论】:

标签: angular typescript ionic2


【解决方案1】:

试试看,希望对你有帮助

totalAmount:number = 0;
for(let i=0;i<this.data.length;i++){
    totalAmount = totalAmount  + this.data[i].cart_subtotal;
}

如果cart_subtotal 给出字符串值,则使用:

totalAmount = totalAmount  + parseInt(this.data[i].cart_subtotal);

【讨论】:

    【解决方案2】:

    我认为更好(更现代)的方法是使用 reduce 函数,因为求和是 reduce 函数的典型示例。你可以这样做:

    let sum = ((items, prop) => {
        return arr.reduce((a, b) => {
            return a + b.prop;
        }, 0)
    })
    
    let sum = sum(cartInfo, 'cart_subtotal')
    

    这不是一个经过测试/工作的示例,但应该让您很好地了解如何以实用和现代的方式实现这种行为:)

    【讨论】:

      【解决方案3】:

      您需要使用*ngFor 指令。 Here 是官方文档的链接,展示了如何使用 *ngFor 指令。在您的情况下,您需要使用对象中的属性,因此我在下面的示例中添加了属性,该示例来自 Angular 文档。您可以使用标准点表示法访问每个单独对象的属性。

      来自文档

      <ul>
          <li *ngFor="let hero of heroes">
              {{ hero.firstName }} {{ hero.lastName }}
          </li>
      </ul>
      

      更新

      因此,如果您只想将所有cart_subtotals 相加,那么您需要在组件中声明一个属性,然后在向数组中添加新对象时更新grandTotal。我不知道您如何将项目添加到数组中,但是每次添加新项目时都需要执行下面相应标记的部分。看起来您的小计也是字符串形式的,因此您需要先解析它们,然后才能对它们进行任何数学运算。

      // Declare in your component
      private grandTotal: number = 0;
      
      // Run anytime an object is added to the array.
      updateGrandTotal() {
          // Instantiate a temporary new grand total variable.
          let newGrandTotal = 0;
          // Iterate over each cart item.
          this.carts.forEach(_Cart => {
              // Add the current cart subtotal to the new grand total.
              newGrandTotal = newGrandTotal + parseInt(_Cart.cart_subtotal)
          })
          // Save the New GrandTotal to the Grand Total Property.
          this.grandTotal = newGrandTotal;
      }
      

      【讨论】:

      • 感谢您的回复先生,先生,我想要发生的事情是我想在我的 ts 先生中展示它。我能做到。我所做的是这样的: this.price = this.data[0].cart_subtotal;我想循环data[0],这样就不用一个一个做。
      • 我不确定*ngFor 是 OP 正在寻找的;他们试图合计迭代项目的值,这将在打字稿中完成,而不是在 HTML 中。我确实同意,我认为这不是一个经过充分研究的问题,这就是为什么我只发表评论而没有提供官方答案的原因。
      • 感谢@Claies,这正是想要的结果
      • 我明白了,对象是如何注入到数组中的?既然您正在使用 Angular,我确定您是以某种方式异步添加它们的?
      猜你喜欢
      • 2022-08-21
      • 2023-02-25
      • 2021-04-26
      • 1970-01-01
      • 2013-08-19
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多