gpt4 book ai didi

javascript - 转置对象数组中的数据

转载 作者:行者123 更新时间:2023-11-28 13:01:18 25 4
gpt4 key购买 nike

我有以下数据,希望将收入转置为各个年份的值:

当前数据:

[{"year": 2017, "month": "Jan", "revenue": 2000},
{"year": 2017, "month": "Feb", "revenue": 3000},
{"year": 2017, "month": "Mar", "revenue": 1000},
{"year": 2016, "month": "Jan", "revenue": 5000},
{"year": 2016, "month": "Feb", "revenue": 4000},
{"year": 2016, "month": "Mar" "revenue": 2000}]

预期输出:

[{Month: "Jan", "2017": 2000, "2016": 5000},
{Month: "Feb", "2017": 3000, "2016": 4000},
{Month: "Mar", "2017": 1000, "2016": 2000}]

我一直在尝试不同的方法,但没有成功。另外,将来我可能会有与一月和三月不同的月份,因此任何不限于三个月的解决方案。

最佳答案

一个基本计划是创建一个以月份为关键字的新对象,并在您经历的过程中逐年添加。 reduce() 使其非常简洁:

let dates = [
{"year": 2017, "month": "Jan", "revenue": 2000},
{"year": 2017, "month": "Feb", "revenue": 3000},
{"year": 2017, "month": "Mar", "revenue": 1000},
{"year": 2016, "month": "Jan", "revenue": 5000},
{"year": 2016, "month": "Feb", "revenue": 4000},
{"year": 2016, "month": "Mar", "revenue": 2000}
]

// You only want an array of values, so just return Object.values()
let d = Object.values(dates.reduce((a, c) =>{
// either use the existing entry or create a new one
// with month already set
(a[c.month] || (a[c.month] = {Month: c.month}))[c.year] = c.revenue;
return a;
}, {}))

console.log(d)

:

关于javascript - 转置对象数组中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50183690/

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