1

I want to use JSONata to do the grouping of json objects in an array based on a key within the JSON object.

For example, I want to group the cars based on their names for the JSON example given below.

[
  {
    "car" : "audi",
    "color" : "blue",
    "reg" : 133434
  },
   {
    "car" : "benz",
    "color" : "red",
    "reg" : 134444
  },
   {
    "car" : "audi",
    "color" : "red",
    "reg" : 134884
  }
]

Expected output

{
  "audi" : [
    {
    "car" : "audi",
    "color" : "blue",
    "reg" : 133434
    },
    {
    "car" : "audi",
    "color" : "red",
    "reg" : 134884
    }
  ],
  "benz" : [
    {
    "car" : "benz",
    "color" : "red",
    "reg" : 134444
    }
   ]
}
CC.
  • 442
  • 4
  • 11
ARUN KUMAR
  • 79
  • 1
  • 7
  • Does this answer your question? [javascript | Object grouping](https://stackoverflow.com/questions/21776389/javascript-object-grouping) – errorau Dec 19 '20 at 12:40
  • I don't think that this question is a duplicate as it asks explicitly for a JSONata query. – CC. Dec 19 '20 at 12:44

1 Answers1

1
$${car: [$.{"car": car, "color": color, "reg": reg}]}

The documentation almost gives the solution:

https://docs.jsonata.org/sorting-grouping

To make sure that the values (even if there is only a single one) for each group is stored in an array, an explicit list construction with [...] is needed.

CC.
  • 442
  • 4
  • 11