如何将一个打字稿数组与该数组内对象的键分组? [英] How to groupBy a typescript array with a Key of an object inside that array?
本文介绍了如何将一个打字稿数组与该数组内对象的键分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组 products
,需要按 Product._shop_id
分组.
I have an array products
that needs to be grouped by 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);
}
}
这是实现此目的的方法.但是我需要对象密钥才能使其正常工作.
Here is the method to achieve this. But I need the Object Key to make it work.
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];
}
}
我正在尝试从 products
数组中获取按 _shop_id
分组的不同数组.像这样:
I'm trying to get different arrays grouped by _shop_id
from products
array.
Like this:
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来提取它:
Since your _shop_id
belongs to a nested object, you're probably best off passing a lambda to extract it:
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());
}
}
这篇关于如何将一个打字稿数组与该数组内对象的键分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文