Javascript:转置json数据

时间:2018-05-04 22:11:08

标签: javascript

我有以下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}]

我一直在尝试不同的方法,但没有成功。同样在将来我可能会有几个月不同于Jan-Mar,所以任何解决方案都不能限制在三个月内。

2 个答案:

答案 0 :(得分:4)

基本计划是将一个新对象设为当月的关键字,并在您经历时添加每年。 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)




答案 1 :(得分:1)

您可以使用ES6语法Array.reduce使用您拥有的数据构建阵列。



const values = [{
    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,
  }
];

// Use destructuration to access each data
const transformedValues = values.reduce((tmp, {
  month,
  year,
  revenue,
}) => {
  // Look for the month in tmp
  const monthInTmp = tmp.find(y => y.Month === month);

  // If it do not exist, push it
  if (!monthInTmp) {
    tmp.push({
      Month: month,

      // use the following syntax [var] to use a dynamical key
      [year]: revenue,
    });

    return tmp;
  }

  // if it exists update it
  // handle the case when we have two revenue in same year
  if (monthInTmp[year]) {
    monthInTmp[year] += revenue;
  
    return tmp;
  }
  
  monthInTmp[year] = revenue;

  return tmp;
}, []);

console.log(transformedValues );