Map.groupBy()
注意: 在某些瀏覽器的一些版本中,此方法被實現為 Array.prototype.groupToMap() 方法。由於 Web 相容性問題,它現在被實現為一個靜態方法。有關詳細資訊,請檢視 瀏覽器相容性表格。
Map.groupBy() 靜態方法使用提供的回撥函式返回的值來對給定可迭代物件的元素進行分組。最終返回的 Map 使用測試函式返回的唯一值作為鍵,這些鍵可用於獲取每個組中的元素陣列。
該方法主要用於對與物件關聯的元素進行分組,特別是在該物件可能隨時間變化的情況下。如果該物件是不可變的,你可能更傾向於使用字串來表示它,並使用 Object.groupBy() 來對元素進行分組。
試一試
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 9 },
{ name: "bananas", type: "fruit", quantity: 5 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 12 },
{ name: "fish", type: "meat", quantity: 22 },
];
const restock = { restock: true };
const sufficient = { restock: false };
const result = Map.groupBy(inventory, ({ quantity }) =>
quantity < 6 ? restock : sufficient,
);
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]
語法
Map.groupBy(items, callbackFn)
引數
返回值
一個 Map 物件,其中包含每個組的鍵,每個鍵都分配給一個包含該組相關元素的陣列。
描述
Map.groupBy() 對可迭代物件中的每個元素呼叫一次提供的 callbackFn 函式。回撥函式應返回一個值,指示相關元素的組。callbackFn 返回的值用作 Map.groupBy() 返回的 Map 的鍵。每個鍵都有一個關聯的陣列,其中包含回撥函式返回相同值的所有元素。
返回的 Map 中的元素與原始可迭代物件中的元素相同(不是深複製)。更改元素的內部結構將在原始可迭代物件和返回的 Map 中都得到反映。
當你需要對可能隨時間變化而變化的特定物件相關的資訊進行分組時,此方法非常有用。這是因為即使物件被修改,它仍將繼續作為返回的 Map 的鍵。如果你改為建立物件的字串表示形式並在 Object.groupBy() 中將其用作分組鍵,那麼你必須在原始物件及其表示形式之間維護對映關係,以便在物件發生變化時也能正確對映。
注意: 要訪問返回的 Map 中的組,你必須使用最初用作 Map 中鍵的同一個物件(儘管你可以修改其屬性)。你不能使用另一個碰巧具有相同名稱和屬性的物件。
Map.groupBy 不會讀取 this 的值。它可以用於任何物件,並返回一個新的 Map 例項。
示例
使用 Map.groupBy()
首先,我們定義一個包含表示不同食品庫存的物件的陣列。每種食品都有一個 type 和一個 quantity。
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 9 },
{ name: "bananas", type: "fruit", quantity: 5 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 12 },
{ name: "fish", type: "meat", quantity: 22 },
];
下面的程式碼使用 Map.groupBy(),並提供一個箭頭函式,該函式根據元素 quantity < 6 是否成立,返回 restock 或 sufficient 鍵。返回的 result 物件是一個 Map,因此我們需要使用鍵呼叫 get() 來獲取陣列。
const restock = { restock: true };
const sufficient = { restock: false };
const result = Map.groupBy(inventory, ({ quantity }) =>
quantity < 6 ? restock : sufficient,
);
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]
請注意,函式引數 { quantity } 是 物件解構語法用於函式引數 的一個基本示例。它會解構作為引數傳遞的物件中的 quantity 屬性,並將其賦值給函式體中名為 quantity 的變數。這是一種訪問函式內元素相關值的非常簡潔的方式。
Map 的鍵可以被修改並仍然使用。但是,你不能重新建立鍵然後仍能使用它。因此,任何需要使用該對映的東西都必須保留對其鍵的引用,這一點非常重要。
// The key can be modified and still used
restock["fast"] = true;
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]
// A new key can't be used, even if it has the same structure!
const restock2 = { restock: true };
console.log(result.get(restock2)); // undefined
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-map.groupby |
瀏覽器相容性
載入中…