javascript - 如何使用该数组内的对象的键对打字稿数组进行分组?
问题描述
我有一个数组products
需要按Product._shop_id
.
export class Product {
_id: string;
_shop_id: string;
}
export class Variant { variant_id: string; }
export interface ShoppingCart {
Variant: Variant;
Product: Product;
quantity: number;
totalPrice: number;
}
export class CartComponent implements OnInit {
products: ShoppingCart[] = [];
ngOnInit(){
this.products = [
{Variant: {variant_id: '1'}, Product: {_id: '1', _shop_id:'1'}, quantity: 5, totalPrice: 600},
{Variant: {variant_id: '2'}, Product: {_id: '2', _shop_id:'2'}, quantity: 4, totalPrice: 500},
{Variant: {variant_id: '5'}, Product: {_id: '3', _shop_id:'2'}, quantity: 3, totalPrice: 400}
]
}
someMethod(){
const productsByShop = this.utils.groupBy(this.products, key);
}
}
这是实现这一目标的方法。但我需要对象键才能使其工作。
export class Utils {
constructor() { }
groupBy(list, key) {
const map = new Map();
list.forEach((item) => {
const collection = map.get(key);
if (!collection) {
map.set(key, [item]);
} else {
collection.push(item);
}
});
return Array.from(map)[0][1];
}
}
我正在尝试_shop_id
从数组中获取不同的products
数组。像这样:
array1: [ {Variant: {variant_id: '1'}, Product: {_id: '1', _shop_id:'1'}, quantity: 5, totalPrice: 600} ]`
array2: [ {Variant: {variant_id: '2'}, Product: {_id: '2', _shop_id:'2'}, quantity: 4, totalPrice: 500},
{Variant: {variant_id: '5'}, Product: {_id: '3', _shop_id:'2'}, quantity: 3, totalPrice: 400} ]`
解决方案
由于您_shop_id
属于嵌套对象,因此您最好传递一个 lambda 来提取它:
someMethod(){
const productsByShop = this.utils.groupBy(this.products,
(product) => product.Product._shop_id);
}
// ...
export class Utils {
constructor() { }
groupBy<T, K>(list: T[], getKey: (item: T) => K) {
const map = new Map<K, T[]>();
list.forEach((item) => {
const key = getKey(item);
const collection = map.get(key);
if (!collection) {
map.set(key, [item]);
} else {
collection.push(item);
}
});
return Array.from(map.values());
}
}
推荐阅读
- c# - 实体类型'IdentityUserLogin
' 需要在添加索引时定义主键 - powershell - 在使用 -format nor-DisplayHint 时将小时添加到日期时间不起作用
- ios - 在 uiimagecontroller 中跳过视频预览
- javascript - Node.Js 中有海象运算符吗?
- sql - 查询为单个计数返回多行
- nlp - 双向RNN实现pytorch
- rest - 我调用 REST API(使用实体框架)的 Windows 应用程序如何使用 EF 生成的模型
- python - 使用带有列表的try-except块时Python中的语法错误
- html - 相同的屏幕尺寸不同的 css 行为 - 响应式网站材料 ui
- python - 为什么第一个打印语句的字符串会在 python 中打印?