我有下面data
个对象,其中包含有关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",
},
],
},
],
};
到目前为止,我已经使用以下代码过滤了进行了购买的客户:
const customersWhoPurchased = data["customers"].filter((c) =>
data["purchases"].find((p) => p.customerId === c.id)
)
所以这customersWhoPurchased
个现在看起来是这样的:
[ { id: 'c01', firstname: 'Rachel', lastname: 'Jane' },
{ id: 'c02', firstname: 'Leilah', lastname: 'Mandi' },
{ id: 'c03', firstname: 'Campbell', lastname: 'Kendall' } ]
我现在想要实现的是判断data
对象中每个客户的购买,判断purchases.purchases
数组中的productId
并将其与products
匹配,然后返回客户购买的每个产品的name
,并将它们添加到customersWhoPurchased
数组中的附加键值对中,值是每个产品名称的array.所以最终的结果应该是这样的.
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'] },
],
希望这对我在这里努力实现的目标是有意义的.
最棒的不仅是解决方案,而且是关于你如何解决问题的解释/理论.我真的在努力提高关于复杂对象的问题解决能力,所以这里的任何帮助都会有很大帮助.