I'm struggling to group items from one array based on a value from another array, but I can't seem to figure out the right approach.
In my orders array, each object has a key-value pair like id: 999324
. Now, in another array for products, there are multiple objects with different or matching ids like orderlineId: 999324
. My goal is to group together those objects with matching IDs.
Order array
[{
"agreement": null,
"channel": null,
"collection": "Colect 2019",
"comment": "Comment here",
"customerNo": "140159",
"customerOrderReference": "CustomerOReference",
"customerPriceGroup": "1,7",
"erpOrderReference": "1337ORDERREFERENCE",
"externalUrl": null,
"id": 99945333,
},
{
...
]
Products array
[{
"crossReference": null,
"currency": "EU",
"deliverySubBlock": null,
"eanCode": "8717945155406",
"grossLineAmount": 99.99,
"grossWholesalePrice": 99.99,
"id": 1156718740,
"orderlineId": 99945334,
},
{
...
}]
The desired output would be an array of orders with nested arrays containing all products that match the orders.id
and products.orderlineId
.
[{
{
"agreement": null,
"channel": null,
"collection": "Colect 2019",
...
"id": 99945334,
"orderLines" [
{
...
},
...
},
{
...
}]
I've attempted various methods, such as:
for(let i=0; i<orders.length; i++) {
merged.push({
...products[i],
...(orders.find((itmInner) => itmInner.id === products[i].orderlineId))}
);
}
But it's not yielding the correct result. Any guidance on what I may be doing wrong would be greatly appreciated.
I hope I've explained my issue clearly since this is my first post on Stack Overflow.