我正试图弄清楚如何在一个非常大的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方法来获取数据,但无法计数。如果您有任何想法,或者最好是文档,可以在这里链接,请在这里告诉我!
答案 0 :(得分:1)
您可以在迭代时计算它们。
要为元素分配值,可以获取对象的所有条目,并使用键作为id并将值分配给元素。
使用的技术:
Array#forEach
用于迭代数组,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>
答案 1 :(得分:0)
为数组命名
var Arr = [{ 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 }];
// and run a simple for loop to filter both values from each item
var Booked = 0,
Free = 0;
for (var i = 0; i < Arr.length; i++) {
if (Arr[i].status == "booked") {
Booked++;
} else {
Free++;
}
};
// now you can put these 2 variables into html like
document.getElementById("booked").innerHTML = Booked;
document.getElementById("free").innerHTML = Free;
Seats Booked: <a id="booked"></a> Seats Free: <a id="free"></a>