0

我有以下数据:

const rawData=[
  {
    Order_Date: "2020-08-11",
    Region: "South",
    Product_Name: "Bookcase",
    Sales: 261.96
  },
  {
    Order_Date: "2020-08-13",
    Region: "South",
    Product_Name: "Stacking Chairs",
    Sales: 731.94
  },
 {
    Order_Date: "2020-08-11",
    Region: "Central",
    Product_Name: "Table",
    Sales: 200
  },
  {
    Order_Date: "2020-08-11",
    Region: "East",
    Product_Name: "Chairs",
    Sales: 350
  },
  {
    Order_Date: "2020-10-06",
    Region: "South",
    Product_Name: "Stacking Chairs",
    Sales: 700.45
  },
 {
    Order_Date: "2020-10-06",
    Region: "Central",
    Product_Name: "Chairs",
    Sales: 500
  },
  {
    Order_Date: "2020-12-06",
    Region: "East",
    Product_Name: "Self-Adhesive Address Labels for Typewriters by Universal",
    Sales: 14.62
  },
  {
    Order_Date: "2019-11-15",
    Region: "East",
    Product_Name: "Table",
    Sales: 957
  },
  {
    Order_Date: "2019-11-10",
    Region: "East",
    Product_Name: "Eldon Fold",
    Sales: 22
  }
]

预期输出:

[
  {
    Order_Date: "2020-08",
    East: 350,
    South: 993.90,
    Central: 200
  },
  {
    Order_Date: "2020-10",
    East: 0,
    South: 700.45,
    Central: 500
  },
  {
    Order_Date: "2019-11",
    East: 989,
    South: 0,
    Central: 0
  },
  {
    Order_Date: "2020-12",
    East: 14.62,
    South: 0,
    Central: 0
  },
]

我想按年和月(“YYYY-MM”)对所有 Order_Date 进行分组,并为每个 Order_Date (“YYYY-MM”)组的每个区域值放置销售额总和。

我需要像Nivo 条形图数据一样转换数据。但我无法获得任何关于转换数据的 nivo 文档。

4

1 回答 1

1

您可以拥有动态密钥Order_Date并根据此密钥对数据进行分组。您可以总结Sales每个区域的重复键值。

const rawData=[ { Order_Date: "2020-08-11", Region: "South", Product_Name: "Bookcase", Sales: 261.96 }, { Order_Date: "2020-08-13", Region: "South", Product_Name: "Stacking Chairs", Sales: 731.94 }, { Order_Date: "2020-08-11", Region: "Central", Product_Name: "Table", Sales: 200 }, { Order_Date: "2020-08-11", Region: "East", Product_Name: "Chairs", Sales: 350 }, { Order_Date: "2020-10-06", Region: "South", Product_Name: "Stacking Chairs", Sales: 700.45 }, { Order_Date: "2020-10-06", Region: "Central", Product_Name:"Chairs", Sales: 500 }, { Order_Date: "2020-12-06", Region: "East", Product_Name: "Self-Adhesive Address Labels for Typewriters by Universal", Sales: 14.62 }, { Order_Date: "2019-11-15", Region: "East", Product_Name: "Table", Sales: 957 }, { Order_Date:"2019-11-10", Region: "East", Product_Name: "Eldon Fold", Sales: 22 } ],
      result = Object.values(rawData.reduce((r, {Order_Date, Region, Sales}) => {
        const date = Order_Date.substr(0, 7);
        r[date] ??= {Order_Date: date, East: 0, South: 0, Central: 0};
        r[date][Region] += Sales;
        return r;
      }, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

于 2021-09-01T19:04:43.583 回答