這是一個資料陣列:
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
}
]
我需要以表格形式(Angular)表示資料:
Fruits
France 2020 2021
Germany 2020 2021
Gain
Spain 2020 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);
uj5u.com熱心網友回復:
如果你想分組productType,下面是你的參考
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532608.html
上一篇:如果值發生變化,則僅從流中獲取值
下一篇:如何系結另一個自定義組件下拉值?
