I have a nested array of objects. I'm trying to group product objects that have the same value.
Each objects has a vendor property containing an email. I am trying to group the objects by matching vendor email
This is how my database looks like:
[
{
_id: "622d70a49bd88b1599026318",
products: [
{
_id: "6223186e2278d4e502f5264a",
title: "Product number 1",
price: 600,
cartQuantity: 1,
vendor: {email: "[email protected]"}
},
{
_id: "622d4e9f9bd88b1599026317",
title: "asdas",
price: 100,
cartQuantity: 5,
vendor: {
email: "[email protected]"
}
},
{
_id: "622d4e9f9bd88b1599026317",
title: "asdas",
price: 100,
cartQuantity: 5,
vendor: {
email: "[email protected]"
}
}
]
}]
I am trying to do it with the reduce method but the problem is with using map inside the reduce. It repeats the object many times. I am also unable to get the grouped objects.
const groupedMap = db.reduce(
(entryMap, e) => e.products.map((product) => entryMap.set(product.vendor.email, [...entryMap.get(product)||[], product])),
new Map()
);
My expectation is:
[0: {"[email protected]" => Array(1)}
key: "[email protected]"
value: [{_id: '6223186e2278d4e502f5264a', title: 'Product number 1', price: 600, cartQuantity: 1, vendor: {email: "[email protected]"}}],
1: {"[email protected]" => Array(2)}
key: "[email protected]"
value: [{_id: '6223186e2278d4e502f5264a', title: 'Product number 1', price: 600, cartQuantity: 1, vendor: {email: "[email protected]"}},
{_id: '6223186e2278d4e502f5264a', title: 'Product number 1', price: 600, cartQuantity: 1, vendor: {email:"[email protected]"}}
]
]
