_lodash sort and group arrays in object by itemId, color & size and get sum

Viewed 50

I have array with objects with array. I need group them by itemId, itemColor and itemSize and get sum of items.

For this example I have 2 objects, but they can be many more.

If shop are no matches then I need to set 0 value.

  [
      {
        "_id": "shop 1",
        "items": [
          [
            {
              "itemId": "111",
              "itemColor": "red",
              "itemSize": "xxl",
              "itemCount": 1,
              "itemName": "example name 1"
            },
            {
              "itemId": "222",
              "itemColor": "green",
              "itemSize": "xl",
              "itemCount": 1,
              "itemName": "example name 2"
            }
          ]
        ]
      },
      {
        "_id": "shop 2",
        "items": [
          [
            {
              "itemId": "111",
              "itemColor": "red",
              "itemSize": "xxl",
              "itemCount": 3,
              "itemName": "example name 1"
            },
            {
              "itemId": "222",
              "itemColor": "blue",
              "itemSize": "L",
              "itemCount": 1,
              "itemName": "example name 2"
            }
          ]
        ]
      },

this is output I need:

+----------------+-------+------+--------+--------+-----+
| itemName       | color | size | shop 1 | shop 2 | sum |
+================+=======+======+========+========+=====+
| example name 1 | red   | xxl  | 1      | 3      | 4   |
+----------------+-------+------+--------+--------+-----+
| example name 2 | green | xl   | 1      | 0      | 1   |
+----------------+-------+------+--------+--------+-----+
| example name 2 | blue  | l    | 0      | 1      | 1   |
+----------------+-------+------+--------+--------+-----+

I tried to group with mongodb aggregation, but I realized that it is easier to do this with lodash.

0 Answers
Related