Look out for JavaScript's Object.groupBy(items, callbackFn)
Modurotolu Olokode
Experienced Web Developer | Full Stack Specialist | Expert in JavaScript, TypeScript, React, and Node.js | Passionate about Crafting High-Performance Solutions.
If ever you've had to convert an Array of Objects:
to an Object with Array of data as the Key in the key-value pair
This may be for you.
The transformation above will be achieved simply by grouping by type:
Object.groupBy(inventory, ({ type }) => type)
Furthermore, you can group by inference from one or more properties of the elements:
function myCallback({ quantity }) {
return quantity > 5 ? "ok" : "restock";
}
const result2 = Object.groupBy(inventory, myCallback);
/* Result is:
{
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 }
]
}
*/
Above is a similar example that puts the items into 2 different categories based on a value calculated from the quantity.
Used to be implemented as Array.prototype.group() on some browsers.