为 Nvd3 图表转换 Json 格式 Angular 2

Convert Json format for Nvd3 chart Angular 2

我有这样的数据:

data2 = [
        {
            "earnings_type": "C",
            "payment_date": "Jan",
            "amount": 10
        },
        {
            "earnings_type": "C",
            "payment_date": "Jan",
            "amount": 10
        }, {
            "earnings_type": "E",
           "payment_date": "Jan",
            "amount": 10
        },
    ]

我需要把它转换成这个

data2 = [
        {
            "key": "C", 
            "values":
            [
                {
                    "label": "15-01-2017", 
                    "value": 20 
                },
                {
                    "label": "17-02-2017",
                    "value": 16
                }
            ]
        }, 
        {
            "key": "E",  
            "values": [
                {
                    "label": "15-01-2017",
                    "value": 15
                }
            ]
        }
        ];

我需要做的是通过数据找到 earnings_type 是 C 的所有项目,并将其作为键并将值放在它下面。然后对 earnings_type 为 A 的所有项目执行相同的操作。

如有任何帮助,我们将不胜感激。

使用Array.prototype.reduce。不确定如何将 payment_date 变成标签,因为样本数据有 payment_date 的月份名称,但标签有完整的日期。如果您需要使用月中点,我相信您可以根据下面的代码弄清楚如何做到这一点。

const origData = [
  {
    earnings_type: "C",
    payment_date: "Jan",
    amount: 10
  },
  {
    earnings_type: "C",
    payment_date: "Jan",
    amount: 10
  },
  {
    earnings_type: "E",
    payment_date: "Jan",
    amount: 10
  }
];

const newData = origData.reduce((result, origDataPoint) => {
  const matchingDataPoint = result.find(
    datapoint => datapoint.key === origDataPoint.earnings_type
  );
  if (!matchingDataPoint) {
    result.push({
      key: origDataPoint.earnings_type,
      values: [
        {
          label: origDataPoint.payment_date,
          value: origDataPoint.amount
        }
      ]
    });
  } else {
    matchingDataPoint.values.push({
      label: origDataPoint.payment_date,
      value: origDataPoint.amount
    });
  }
  return result;
}, []);