| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy | [Back] [Original] |
Get to know MDN better
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 result = Object.groupBy(inventory, ({ quantity }) =>
quantity < 6 ? "restock" : "sufficient",
);
console.log(result.restock);
// [{ name: "bananas", type: "fruit", quantity: 5 }]
Object.groupBy(items, callbackFn)
Object.groupBy() callbackFn 1 callbackFn Object.groupBy()
type quantity
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];
type
const result = Object.groupBy(inventory, ({ type }) => type);
/* :
{
vegetables: [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
],
fruit: [
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 }
],
meat: [
{ name: "goat", type: "meat", quantity: 23 },
{ name: "fish", type: "meat", quantity: 22 }
]
}
*/
1 quantity ok restock
function myCallback({ quantity }) {
return quantity > 5 ? "ok" : "restock";
}
const result2 = Object.groupBy(inventory, myCallback);
/* :
{
restock: [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 }
],
ok: [
{ name: "goat", type: "meat", quantity: 23 },
{ name: "fish", type: "meat", quantity: 22 }
]
}
*/
| ECMAScript 2027 LanguageSpecification # sec-object.groupby |
Objectassign()create()defineProperties()defineProperty()entries()freeze()fromEntries()getOwnPropertyDescriptor()getOwnPropertyDescriptors()getOwnPropertyNames()getOwnPropertySymbols()getPrototypeOf()groupBy()hasOwn()is()isExtensible()isFrozen()isSealed()keys()preventExtensions()seal()setPrototypeOf()values()Object/Function| Web Proxy Viewer | New URL | Original Page |