How to group by array object from values to create new array object of values
Input
var promotions = [
{
"promotionID": 2,
"id": 1,
"qty": 1,
"productID": 1,
"product": "Nu Milk Tea 330ml",
"operator": null
}, {
"promotionID": 2,
"id": 2,
"qty": 2,
"productID": 2,
"product": "Product testing 2",
"operator": 1
}, {
"promotionID": 2,
"id": 3,
"qty": 3,
"productID": 3,
"product": "Golda Coffee Dolce Latte 200ml",
"operator": 2
}, {
"promotionID": 3,
"id": 4,
"qty": 8,
"productID": 54,
"product": "Masker Skrineer 3ply Motif 5pcs",
"operator": null
}, {
"promotionID": 3,
"id": 5,
"qty": 5,
"productID": 53,
"product": "Masker Skrineer 1ply Grey 5pcs",
"operator": 2
}, {
"promotionID": 3,
"id": 6,
"qty": 5,
"productID": 52,
"product": "Oronamin C Drink 120ml",
"operator": 1
}]
I want to make a new array of car objects that's grouped by promotionID
Expected Output
[
{
"promotionID": 2,
"data" : [
{
"promotionID": 2,
"id": 1,
"qty": 1,
"productID": 1,
"product": "Nu Milk Tea 330ml",
"operator": null
}, {
"promotionID": 2,
"id": 2,
"qty": 2,
"productID": 2,
"product": "Product testing 2",
"operator": 1
}, {
"promotionID": 2,
"id": 3,
"qty": 3,
"productID": 3,
"product": "Golda Coffee Dolce Latte 200ml",
"operator": 2
}
]
},
{
"promotionID": 3,
"data" : [
{
"promotionID": 3,
"id": 4,
"qty": 8,
"productID": 54,
"product": "Masker Skrineer 3ply Motif 5pcs",
"operator": null
}, {
"promotionID": 3,
"id": 5,
"qty": 5,
"productID": 53,
"product": "Masker Skrineer 1ply Grey 5pcs",
"operator": 2
}, {
"promotionID": 3,
"id": 6,
"qty": 5,
"productID": 52,
"product": "Oronamin C Drink 120ml",
"operator": 1
}
]
}
]
You could use
reduce
to group promotion by promotionId and then map through the entries to get the final result