The data object below contains information about products, customers & purchases.
const data = {
products: [
{
id: "p01",
name: "Bike Insurance",
},
{
id: "p02",
name: "Car Insurance",
},
{
id: "p03",
name: "Home Insurance",
},
{
id: "p04",
name: "Pet Insurance",
},
],
customers: [
{ id: "c01", firstname: "Rachel", lastname: "Jane" },
{ id: "c02", firstname: "Leilah", lastname: "Mandi" },
{ id: "c03", firstname: "Campbell", lastname: "Kendall" },
{ id: "c04", firstname: "Madonna", lastname: "Sammie" },
],
purchases: [
{
customerId: "c01",
purchases: [
{
productId: "p02",
purchasedAt: "2021-08-03T00:00:00.000Z",
},
{
productId: "p02",
purchasedAt: "2021-08-04T00:00:00.000Z",
},
{
productId: "p01",
purchasedAt: "2021-09-12T00:00:00.000Z",
},
{
productId: "p01",
purchasedAt: "2021-09-12T00:00:00.000Z",
},
],
},
{
customerId: "c03",
purchases: [
{
productId: "p04",
purchasedAt: "2021-08-03T00:00:00.000Z",
},
{
productId: "p04",
purchasedAt: "2021-09-12T00:00:00.000Z",
},
{
productId: "p03",
purchasedAt: "2021-09-12T00:00:00.000Z",
},
{
productId: "p01",
purchasedAt: "2021-09-12T00:00:00.000Z",
},
],
},
{
customerId: "c02",
purchases: [
{
productId: "p01",
purchasedAt: "2021-09-12T00:00:00.000Z",
},
],
},
],
};
I have so far filtered out the customers who have made purchases by using the following code:
const customersWhoPurchased = data["customers"].filter((c) =>
data["purchases"].find((p) => p.customerId === c.id)
)
so the customersWhoPurchased now looks like this:
[ { id: 'c01', firstname: 'Rachel', lastname: 'Jane' },
{ id: 'c02', firstname: 'Leilah', lastname: 'Mandi' },
{ id: 'c03', firstname: 'Campbell', lastname: 'Kendall' } ]
What is the reasoning finding a query to go through the purchases for each customer in the data object, checking productId in the purchases.purchases array and matching that up to the products and then returning the name of each product the customer has purchased and adding them into an additional key value pair in the customersWhoPurchased array, with the value being an array of each product name?
Result:
customers: [
{ id: "c01", firstname: "Rachel", lastname: "Jane", productNames: ['Bike Insurance', 'Car Insurance'] },
{ id: "c02", firstname: "Leilah", lastname: "Mandi", productNames: ['Bike Insurance'] },
{ id: "c03", firstname: "Campbell", lastname: "Kendall", productNames: ['Bike Insurance', 'Home Insurance', 'Pet Insurance'] },
],