This question already has answers here:
Better way to sum a property value in an array
                            
                                (15个答案)
                            
                    
                2年前关闭。
        

    

我试图弄清楚如何在一个非常大的JSON文件中计算不同的值。

下面,我包括了10,000行以上JSON文件中的一小部分。我需要以数字形式计算“状态”:“已预订”和“状态”:“免费”的总金额。

[
  {
    "eventId": 126363,
    "eventKey": "4749466",
    "objectLabelOrUuid": "uuid8083",
    "status": "booked",
    "quantity": 1,
    "ticketType": null,
    "holdTokenHash": null,
    "version": 3,
    "extraData": null
  },
  {
    "eventId": 126363,
    "eventKey": "4749466",
    "objectLabelOrUuid": "uuid11392",
    "status": "free",
    "quantity": 0,
    "ticketType": null,
    "holdTokenHash": null,
    "version": 6,
    "extraData": null
  },
  {
    "eventId": 126363,
    "eventKey": "4749466",
    "objectLabelOrUuid": "uuid8051",
    "status": "booked",
    "quantity": 1,
    "ticketType": null,
    "holdTokenHash": null,
    "version": 2,
    "extraData": null
  }
]


将它们转换为数字形式后,我将把值放在html文档中

Seats Booked: <a id="booked"></a> Seats Free: <a id="free"></a>


预期输出:

Seats Booked: 2 Seats Free: 1


据我了解,我可以使用foreach方法来获取数据,但是我无法对其进行计数。如果您有任何想法或最好是可以在此处链接的文档,请在这里告诉我!

最佳答案

您可以在迭代时计算它们。

要将值分配给元素,可以获取对象的所有条目,并将键用作ID并将值分配给元素。

二手技术:


Array#forEach用于迭代数组,
destructuring assignment,用于获取单个属性,或稍后用于获取数组的两个值,
Object.entries用于获取对象的所有键和值




var data = [{ eventId: 126363, eventKey: "4749466", objectLabelOrUuid: "uuid8083", status: "booked", quantity: 1, ticketType: null, holdTokenHash: null, version: 3, extraData: null }, { eventId: 126363, eventKey: "4749466", objectLabelOrUuid: "uuid11392", status: "free", quantity: 0, ticketType: null, holdTokenHash: null, version: 6, extraData: null }, { eventId: 126363, eventKey: "4749466", objectLabelOrUuid: "uuid8051", status: "booked", quantity: 1, ticketType: null, holdTokenHash: null, version: 2, extraData: null }],
    count = { booked: 0, free: 0 };

window.onload = function() {
    data.forEach(({ status }) => count[status]++);
    Object.entries(count).forEach(([id, value]) =>
        document.getElementById(id).innerHTML = value);
};

Seats Booked: <a id="booked"></a> Seats Free: <a id="free"></a>

10-05 21:11
查看更多