Я хочу оптимизировать этот код.
Предметы
[{
"quantitySold": 1,
"totalAmount": 0,
"totalDiscount": 0,
"categories":
{
"_id": "6008158fb3ea7e42477ef591",
"categoryId": "5fc53d63ac5f5923149eb36b",
"name":
{
"fr": "Hors-catégories",
"en": "Miscellaneaous",
"de": "Verschiedenes"
}
}
},
{
"quantitySold": 4,
"totalAmount": 0,
"totalDiscount": 0,
"categories":
{
"_id": "6006d136b3ea7e27a97ef3be",
"categoryId": "5ffe015e548bc411e48d8918",
"name":
{
"fr": "BD et Mangas"
}
}
},
{
"quantitySold": 6,
"totalAmount": 0,
"totalDiscount": 0,
"categories":
{
"_id": "6006c31cb3ea7e765a7ef39a",
"categoryId": "5fc566fbac5f5923149eb36c",
"name":
{
"fr": "Parfums"
}
}
},
{
"quantitySold": 2,
"totalAmount": 0,
"totalDiscount": 0,
"categories":
{
"_id": "6006d136b3ea7ec5857ef3b9",
"categoryId": "5fc53d63ac5f5923149eb36b",
"name":
{
"fr": "Hors-catégories",
"en": "Miscellaneaous",
"de": "Verschiedenes"
}
}
},
{
"quantitySold": 5,
"totalAmount": 0,
"totalDiscount": 0,
"categories":
{
"_id": "6006d136b3ea7e51e27ef3b5",
"categoryId": "5ff3122453d658f874226382",
"name":
{
"fr": "Jouets"
}
}
},
{
"quantitySold": 11,
"totalAmount": 152.9,
"totalDiscount": 0,
"categories":
{
"_id": "6006c31cb3ea7e638e7ef398",
"categoryId": "5fc53d63ac5f5923149eb36b",
"name":
{
"fr": "Hors-catégories",
"en": "Miscellaneaous",
"de": "Verschiedenes"
}
}
}]
Мне нужно сгруппировать эти предметы по категория:
categorise(articles) {
return articles.reduce((a, c) => {
a[c.categories.categoryId] = a[c.categories.categoryId] || {};
a[c.categories.categoryId]['items'] = a[c.categories.categoryId]['items'] || [];
a[c.categories.categoryId]['items'].push(c);
a[c.categories.categoryId]['category'] = {
name: c.categories.name[this.locale],
totalQty: a[c.categories.categoryId]['items'].reduce((acc, val) => { return acc + val.quantitySold; }, 0),
totalPrice: a[c.categories.categoryId]['items'].reduce((acc, val) => { return acc + val.totalAmount; }, 0)
}
return a;
}, Object.create(null));
}
HTML
<ng-container *ngFor="let a of articles | keyvalue">
<div class="articles__wrapper mb-3 font--bold">
<div class="text-left">{{a?.value?.category?.name}}</div>
<div class="text-left">{{a?.value?.category?.totalQty}}</div>
<div class="text-right">{{a?.value?.category?.totalPrice | numberFormat }}</div>
</div>
<div class="articles__wrapper mb-3" *ngFor="let article of a.value.items">
<div class="text-left">{{article?.name[locale]}}</div>
<div class="text-left">{{article?.quantitySold}}</div>
<div class="text-right">{{article?.totalAmount | numberFormat }}</div>
</div>
</ng-container>
Любая помощь приветствуется. Благодарю.