如何编写一个javascript,从json计算每个客户的总金额



我仍然是javascript和node的初学者,我遇到了一个问题。我有一个包含支付api的文件,我需要计算每个客户的欠款总额。文件如下:

[
{
"paymentId": "fc3a34e6-885e-4baf-8c67-3eeb4c3cd945",
"customer": "Customer1",
"amountInEur": 97
},
{
"paymentId": "00320009-d2d2-43de-8ac3-a82bad36f718",
"customer": "Customer2",
"amountInEur": 51
},
{
"paymentId": "cd44a829-e915-4f85-95bf-fe82dcd5df15",
"customer": "Customer3",
"amountInEur": 57
},
{
"paymentId": "59c2405a-7fc2-435e-a9b1-3065f783869c",
"customer": "Customer2",
"amountInEur": 64
},

而且名单还在继续。客户可能会在名单上出现好几次。所以我需要计算每个客户的欠款。

这就是我目前拥有的

const fs = require("fs");
try {
const jsonString = fs.readFileSync("./logs.json", "utf8");
const data = JSON.parse(jsonString);
console.log(data);
} catch (err) {
console.log(err);
}

所以我可以从json文件中获取数据,甚至可以计算总金额,但我如何计算每个客户的总金额?

您可以使用.reduce()将运行JSON.parse()时收到的数组转换为一个对象,其中键是客户字符串和值-它们欠多少钱,如下所示:

const array = [
{
"paymentId": "fc3a34e6-885e-4baf-8c67-3eeb4c3cd945",
"customer": "Customer1",
"amountInEur": 97
},
{
"paymentId": "00320009-d2d2-43de-8ac3-a82bad36f718",
"customer": "Customer2",
"amountInEur": 51
},
{
"paymentId": "cd44a829-e915-4f85-95bf-fe82dcd5df15",
"customer": "Customer3",
"amountInEur": 57
},
{
"paymentId": "59c2405a-7fc2-435e-a9b1-3065f783869c",
"customer": "Customer2",
"amountInEur": 64
},
];
const amountsByEachCustomer = array.reduce((amountsByEachCustomer, item) => {
// Initialize the amount to 0 when encounter customer for the first time in the loop
if (typeof amountsByEachCustomer[item.customer] === "undefined") {
amountsByEachCustomer[item.customer] = 0;
}
amountsByEachCustomer[item.customer] += item.amountInEur;
return amountsByEachCustomer;
}, {});
console.log(amountsByEachCustomer); // { Customer1: 97, Customer2: 115, Customer3: 57 }

最新更新