我有一個嵌套的物件陣列。我正在嘗試對具有相同價值的產品物件進行分組。下面的物件有一個vendor密鑰,里面也有一封電子郵件。vendor email因此,如果產品相同,我會嘗試對物件進行分組。
這是我的資料庫的樣子`
[
{
_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]"
}
}
]
}]
我正在嘗試使用reduce方法來做到這一點,但問題是在reduce中使用map方法重復物件多次。也沒有能夠得到相同物件的組。
const groupedMap = db.reduce(
(entryMap, e) => e.products.map((product) => entryMap.set(product.vendor.email, [...entryMap.get(product)||[], product])),
new Map()
);
上面的代碼輸出是:

我的期望是:
[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]"}}
]
]
uj5u.com熱心網友回復:
回圈遍歷陣列中的每個專案,查看供應商電子郵件是否作為鍵已經存在于字典中,如果存在則將其推送到該陣列,否則將供應商電子郵件鍵的值設定為等于其中包含當前專案的陣列
請參閱下面的代碼
const data = [{
_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]"
}
}
]
}];
const mapped = {};
data[0].products.forEach(item => {
if (item.vendor.email in mapped) return mapped[item.vendor.email].push(item);
mapped[item.vendor.email] = [item];
});
const expectedFormat = Object.keys(mapped).map(key => {
const o = {};
o[key] = mapped[key];
return o;
});
console.log(expectedFormat)
uj5u.com熱心網友回復:
嘗試制作一個物件,其中 key 是您分組的值。下一步是 foreach,在其中檢查陣列中的每個物件,您要查找的值是否在生成的物件中 - 如果不是,則通過搜索值過濾陣列并將結果添加到物件
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/443107.html
標籤:javascript 数组 反应 目的 减少
