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.
  • 464
  • 4
  • 11
ARUN KUMAR
  • 89
  • 1
  • 9
  • 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

2 Answers2

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.
  • 464
  • 4
  • 11
0
const list =[
  {
    "car" : "audi",
    "color" : "blue",
    "reg" : 133434
  },
   {
    "car" : "benz",
    "color" : "red",
    "reg" : 134444
  },
   {
    "car" : "audi",
    "color" : "red",
    "reg" : 134884
  }
]

const groups = list.reduce((groups, item) => {
  const group = (groups[item.car] || []);
  group.push(item);
  groups[item.car] = group;
  return groups;
}, {});

console.log(groups);
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – jasie Jul 18 '22 at 06:47