I am getting data from API structured like this:
interface ProductModel {
prod_id: string,
brand: string,
...
}
interface OrderModel {
order_id: string,
prod_id: string,
...
}
const data = {
products: ProductModel[],
orders: OrderModel[]
}
What I want is to restructure the data to group the orders of a product and the product info in one object:
const expectedStructure = {
prod_id: string,
brand: string,
...,
orders: OrderModel[]
}
I suppose that with a reduce it could be done easily, but I don't quite understand how it works. Could someone help me with this example?
Reduce can be used but you dont really need it, simple
.mapwith.filterand...spread operator:Adding a little optimization asked in comments using Map class. With that you will only need 1 loop over initial
Ordersarray to build theMapobject and then you will have a constant time of element retrieval: