我有一個JavaScript數組是這樣的:的JavaScript - 分組物品放入數組
var items = [
{ id:1, group:'Produce', name:'Apple', weight: 0.5 },
{ id:2, group:'Produce', name:'Banana', weight: 0.2 },
{ id:3, group:'Meat', name:'Beef', weight: 1.0 },
{ id:4, group:'Meat', name:'Chicken', weight: 0.75 },
{ id:5, group:'Dairy', name:'Milk', weight:1.0 }
];
我想通過這個數組的外觀和動態的他們的小組把他們的陣列。我試過以下,但是,它沒有工作:
var groups = [];
for (var i = 0; i<items.length; i++) {
var groupName = items[i].group;
if (groups.includes(groupName) === false) {
groups[groupName] = new Array();
}
groups[groupName].push(items[i]);
}
基本上,我試圖在JavaScript中創建一個哈希表。關鍵是組名稱,值是該組中項目的Array
。但是,我一直沒有成功。我在這裏錯過了什麼?
非常感謝您的幫助!
「它沒有工作」和「我一直不成功」是不可接受的問題陳述。請明確定義問題,並使標題描述它。謝謝。 –