Sum values from Expression

Hey n8n Community,

Describe the problem/error/question

I am looking for a solution to sum values from the Expression field of my Edit Field node.

Here’s my input:

[
  {
    "OrderId": "1234",
    "OrderDetails": {
      "OrderDetails": [
        {
          "ProductId": "4540",
          "Quantity": "1"
        },
        {
          "ProductId": "4601",
          "Quantity": "1"
        },
        {
          "ProductId": "7144",
          "Quantity": "1"
        }
      ]
    }
  },
  {
    "OrderId": "5678",
    "OrderDetails": {
      "OrderDetails": [
        {
          "ProductId": "4321",
          "Quantity": "1"
        }
      ]
    }
  }
]

I would like to sum the quantities for each item. From my input, the first item would have a result of 3 (1 + 1 + 1), and the second a result of 1. I have tried to fiddle with JMESPath or reduce, but with no luck.

Would someone have a neat one-liner or solution I could use directly from Edit Fields?

What is the error message (if any)?

None.

Please share your workflow

Share the output returned by the last node

Expected output:

[
  {
    "orderTotalItems": 3
  },
  {
    "orderTotalItems": 1
  }
]

Information on your n8n setup

  • n8n version: 1.49.0
  • Database (default: SQLite): Default
  • n8n EXECUTIONS_PROCESS setting (default: own, main): Default
  • Running n8n via (Docker, npm, n8n cloud, desktop app): Docker
  • Operating system: Linux

@jburns , here’s your solution

It involves aggregations nodes

  1. Split Out breaks up the OrderDetails to create individual items for each order item retaining the accompanying and corresponding OrderId (needed for the next node).
  2. Now, it is possible to count all items’ quantities segregated by OrderId with Summarize node.
  3. Finally, Set is used to give the name to the property of the final outcome.
1 Like

Thanks for sharing a solution @ihortom! It worked great with the sample dataset I had provided, while it was not with the original larger dataset I wanted to use this for. But I figured that the JSON input would be different for some orders, and eventually I managed to achieve what I wanted with a Code node and a simple function.

Here’s the working solution with an updated dataset and the Code node:

Thanks again!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.