gpt4 book ai didi

JavaScript:比较数组中的日期并对每个月/年的 "price"求和

转载 作者:行者123 更新时间:2023-12-01 10:25:34 25 4
gpt4 key购买 nike

我有一个包含多个 transactions 的 json 文件,其中包含一个 date 和一个 price 属性。现在我想比较日期,如果它们在同一年和同一年,我想总结价格。

JSON:

transactions: [
{
date: "2017-11-17",
price: "28",
},
{
...
}

JavaScript:

request.onload = function() {
for(const transaction of request.response.transactions) {
let year = new Date(transaction.date).getFullYear();
let month = new Date(transaction.date).getMonth();

console.log(year + ' ' + month); // output: 2017-11 ...
}
};

我试图遍历 json 对象,但我很难找到比较日期的解决方案。

最佳答案

编辑:使用 Object.assign 而不是 Object spread 编辑示例。

您需要使用reduce 来对价格求和。有关详细信息,请参阅评论。

const transactions = [{
date: "2017-11-17",
price: "28",
},
{
date: "2017-12-17",
price: "23",
},
{
date: "2017-11-17",
price: "12",
},
{
date: "2017-10-17",
price: "55",
},
{
date: "2017-11-17",
price: "09",
},
];

const sumTransactions = (transactions) => {

const summed = transactions.reduce((acc, current) => {
// Get the current date object
const date = new Date(current.date);
// Create your key/identifier
const key = `${date.getFullYear()}-${date.getMonth() + 1}`;
// Retreive the previous price from the accumulator
const previousPrice = acc[key]; // Might also return undefined
// Create your temp current price value, and be sure to deal with numbers.
let currentPrice = Number(current.price);
// If you had a previous value (and not undefined)
if (previousPrice) {
// Add it to our value
currentPrice += Number(previousPrice);
}
// Return the future accumulator value
return Object.assign(acc, {
[key]: currentPrice, // new values will overwrite same old values
})
}, {})

// Once we have all values, get the dates, and sort them (default: earlier first)
// Return an array of each value from the summed object to our sortedArray
const sortedArray = Object.keys(summed).sort().map((val) => {
return summed[val];
});

console.log("sortedArray", sortedArray);
};

sumTransactions(transactions);

关于JavaScript:比较数组中的日期并对每个月/年的 "price"求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47715539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com