Look out for JavaScript's Object.groupBy(items, callbackFn)

Look out for JavaScript's Object.groupBy(items, callbackFn)

If ever you've had to convert an Array of Objects:

Array of Objects

to an Object with Array of data as the Key in the key-value pair

Object with Key-Value pairs

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.


要查看或添加评论,请登录

Modurotolu Olokode的更多文章

社区洞察

其他会员也浏览了