我有原始数据通过axios来自mongodb / nestjs API,格式为:
created_at: "date"
quantity: "number"
month: "string"
organization: "string"
state: "string"
category: "string"
year: "date"
_id: "numeber"
通过使用axios并获取数据,我可以生成可管理的输出:
.get(`${server.baseURL}/quantity/quantities`)
.then(response => {
this.rawData = response.data
console.log(this.rawData);
this.rawDataB = this.rawData.map(( {category, quantities} ) => ({category, quantities}))
console.log(this.rawDataB)
})
此rawDataB的控制台日志会产生以下输出数组:
[
{category: "string",
quantities: "number}
]
因为我每个类别都有每月的数据,所以我有大约100个具有这种格式的对象的数组,每个月一个。 所以我有...:
[{category: "string", quantities: "number"}]
从一月到九月的每个月。因此,每个类别都有大约8-9个与同一类别,不同月份和不同数量相关联的对象。
我想将其简化为以下格式,但似乎无法弄清楚:
[
{ category: "string", quantities: "number }
]
对于每个类别-本质上是通过以下外部功能删除重复的类别名称:
export function removeDuplicate (a, b) {
if (a.indexOf(b) < 0) {
a.push(b)
}
return a
}
但是,这样做时,日期键会丢失,仅向我提供数组中的数组:
[
[ "category", number],["category", number]...
]
每个类别的。请注意,该数字已更改为整数而不是字符串
关于我如何能够实现的数据格式的任何想法?
[
{category: "string", totalQuantity: number}
]
答案 0 :(得分:1)
没有图书馆...请注意Object.values()
const rawData = [
{ category: "january", quantities: "2" },
{ category: "february", quantities: "2" },
{ category: "january", quantities: "2" },
{ category: "february", quantities: "2" },
{ category: "january", quantities: "2" },
{ category: "february", quantities: "2" },
{ category: "january", quantities: "2" },
{ category: "february", quantities: "2" }
];
const formattedData = rawData.reduce((previousValue, { category, quantities }) => {
if (!previousValue[category]) {
previousValue[category] = { category, totalQuantity: 0 };
}
previousValue[category].totalQuantity += +quantities;
return previousValue;
}, {});
console.log(Object.values(formattedData));