【发布时间】:2020-09-14 15:32:31
【问题描述】:
我有一个通过 lodash groupBy 函数映射分组数据的对象, 迭代集合并检索以下信息的最佳方法是什么:
- totalProductNumber,
- totalProductSum = Sum(productsNumberInGroup * 价格)
- productsNumberPerGroup
所以输出可能是
let result = {
totalProductNumber: 8,
totalProductSum: 17,
productsNumberPerGroup: [{1:2}, {2:3}, {3:3}] // or sth. like this
}
interface IProduct {
name: string;
color: string;
price: string;
id: number
}
const products = {
"1": [{
"name": "Jim",
"color": "blue",
"price": 1,
"id": 1
},
{
"name": "Jim",
"color": "blue",
"price": 1,
"id": 1
}
],
"2": [{
"name": "Eddie",
"color": "green",
"price": 2,
"id": 2
},
{
"name": "Eddie",
"color": "green",
"price": 2,
"id": 2
},
{
"name": "Eddie",
"color": "green",
"price": 2,
"id": 2
}
],
"3": [{
"name": "Ela",
"color": "pink",
"price": 3,
"id": 3
},
{
"name": "Ela",
"color": "pink",
"price": 3,
"id": 3
},
{
"name": "Ela",
"color": "pink",
"price": 3,
"id": 3
}
]
}
我的假设是使用 Object.entries 或 Object.values
let totalSum: number;
let totalPrices: number[];
Object.values(products)
.map((prod) => {
(prod as IProduct[]).map((p) => {
this.totalPrices.push(Number(p.price)); // here getting Cannot read property 'push' of undefined
});
});
【问题讨论】:
-
你只声明了totalPrices,你没有给它赋值。尝试为其分配一个空数组。
标签: javascript typescript ecmascript-6 lodash