【问题标题】:How to prepare data for table representation?如何为表格表示准备数据?
【发布时间】:2022-11-14 13:28:36
【问题描述】:

这是一个数据数组:

  let data = {
    country: "France",
    productType: "Fruits",
    units: "USD",
    year: 2020,
    value: 5507888,
    rownum: 108
  },
  {
    country: "Germany",
    productType: "Fruits",
    units: "USD",
    year: 2021,
    value: 5849610,
    rownum: 108
  },
  {
    country: "Spain",
    productType: "Gain",
    units: "USD",
    year: 2021,
    value: 5849610,
    rownum: 108
  }
]

我需要以表格形式(Angular)表示数据:

Fruits
   France       2020
   Germany               2021
Gain
   Spain                 2011

我尝试先通过productType 对数据进行分组。然后我需要按县分组。问题是国家在每种产品类型中都重复出现。

function groupBy(list, keyGetter) {
    const map = new Map();
    list.forEach((item) => {
         const key = keyGetter(item);
         const collection = map.get(key);
         if (!collection) {
             map.set(key, [item]);
         } else {
             collection.push(item);
         }
    });
    return map;
}

const grouped = groupBy(filtered, pet => pet.productType); console.log(grouped);

【问题讨论】:

  • 您是否只是从原始数据中获取分组数据(按产品类型分组)?如果是这样,您可以使用reduce() 进行操作

标签: javascript angular


【解决方案1】:

如果你想按productType分组,下面是你的参考

let data = [{
    country: "France",
    productType: "Fruits",
    units: "USD",
    year: 2020,
    value: 5507888,
    rownum: 108
  },
  {
    country: "Germany",
    productType: "Fruits",
    units: "USD",
    year: 2021,
    value: 5849610,
    rownum: 108
  },
  {
    country: "Spain",
    productType: "Gain",
    units: "USD",
    year: 2021,
    value: 5849610,
    rownum: 108
  }
]

let result = data.reduce((a,c) =>{
  let type = c.productType
  a[type] = (a[type]??[])
  a[type].push(c)
  return a
},{})

console.log(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 2013-07-08
    相关资源
    最近更新 更多