Home > Software engineering >  How to prepare data for table representation?
How to prepare data for table representation?

Time:11-13

Here is an array of data:

  let data = {
    country: "France",
    productType: "Fruits",
    units: "USD",
    year: 2020,
    value: 5507888,
    rownum: 108
  },
 {
    country: "France",
    productType: "Fruits",
    units: "USD",
    year: 2021,
    value: 5507888,
    rownum: 108
  },
  {
    country: "Germany",
    productType: "Fruits",
    units: "USD",
    year: 2020,
    value: 5849610,
    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
  }
]

I need to represent data for table form (Angular):

Fruits
   France       2020     2021
   Germany      2020     2021
Gain                
   Spain        2020     2011

I have tried to group data first by productType. Then I need to group by county. Problem is the countries are repeated in each product type.

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);

CodePudding user response:

If you want to group by productType,below is a reference for you

let data = [{
    country: "France",
    productType: "Fruits",
    units: "USD",
    year: 2020,
    value: 5507888,
    rownum: 108
  },
 {
    country: "France",
    productType: "Fruits",
    units: "USD",
    year: 2021,
    value: 5507888,
    rownum: 108
  },
  {
    country: "Germany",
    productType: "Fruits",
    units: "USD",
    year: 2020,
    value: 5849610,
    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]??[]
  
  let record = a[type].find(i => i.country == c.country)
  if(record){
    record.year.push(c.year)
  }else{
    a[type].push({country:c.country,year:[c.year]})
  }
  return a
},{})

console.log(result)

  • Related