Search code examples
jsonjsonata

How to merge object with same keys using JSONATA


I have a JSON data array of objects and I want to prepare another array where object with matching keys get merge and there count value should add up. I am using JSONATA.

Input:

[
{
"name" : "t1",
"count": 1
},
{
"name":"t1",
"count": 2
},
{
"name":"t2",
"count": 4
},
]

Expected Output:

[
{
"name" : "t1",
"count": 3
},
{
{
"name" : "t2",
"count": 4
}
]

Solution

  • Check out the reduce operator in docs: https://docs.jsonata.org/path-operators#---reduce and some grouping examples: https://docs.jsonata.org/sorting-grouping#grouping

    After you have it aggregated into an object, $each function is a nice way to turn it back into an array: https://docs.jsonata.org/object-functions#each

    $${ name: $sum(count) } 
      ~> $each(function($value, $key) {
        { "name": $key, "count": $value }
      })
    

    Live example: https://stedi.link/1oARv4p

    Keep in mind that you can also use the $reduce function and write all of your grouping logic inside if you prefer such code style: https://stedi.link/99gVGwm