首页 > 解决方案 > 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}]

我一直在尝试不同的方法,但没有成功。同样在未来,我可能有几个月与一月至三月不同的月份,因此任何解决方案都不限于三个月。

标签: javascript

解决方案


一个基本的计划是创建一个新的对象作为月份的键,并在你经历时每年添加。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)


推荐阅读