javascript - Javascript:转置 json 数据
问题描述
我有以下 json 数据,并希望将收入作为个别年份的值进行转置:
当前数据:
[{"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}]
我一直在尝试不同的方法,但没有成功。同样在未来,我可能有几个月与一月至三月不同的月份,因此任何解决方案都不限于三个月。
解决方案
一个基本的计划是创建一个新的对象作为月份的键,并在你经历时每年添加。recduce()
使它非常简洁:
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)
:
推荐阅读
- java - 使用 Java 8 构建的 GraalVM 本机映像失败,并出现错误 com.oracle.svm.core.hub.DynamicHub.getGenericInfo() 方法在此平台不可用
- javascript - 如何使用 npm(pact 文件)一起运行多个 .js 测试文件?
- sql - 将星期几名称转换为星期几编号 Vertica
- python - 为什么我的图像加载到数据集中都是白色的?
- google-apps-script - 通过 Google Apps 脚本获取每张幻灯片的 lh3.googleusercontent.com 链接
- c - 测试 FPE 和陷阱 FPE 有什么区别?
- java - Spring Webclient decode custom application/multipart-related,application/dicom (Wado-RS)
- c++ - c++中模板类的重载运算符ostream不起作用
- php - ->toArray() 给出空数组而不是对象
- c# - 移除 android 启动器图标周围的白色容器