如何使用JSONata按指定键对JSON数组中的对象进行分组
Grouping JSON array objects by a specified key using JSONata
To group your array of car objects by the car key, you can use JSONata's built-in $groupBy function—it’s tailored exactly for this kind of grouping task.
Input Data
[ { "car": "audi", "color": "blue", "reg": 133434 }, { "car": "benz", "color": "red", "reg": 134444 }, { "car": "audi", "color": "red", "reg": 134884 } ]
JSONata Expression
$groupBy($, "car")
Explanation
$refers to the entire input array (the root context for this query)."car"is the property selector—JSONata uses the value of this property from each object as the key in the final grouped object.- The
$groupByfunction handles all the heavy lifting: it iterates through the array, groups objects with matchingcarvalues, and collects each group into an array under the corresponding key.
Result
{ "audi": [ { "car": "audi", "color": "blue", "reg": 133434 }, { "car": "audi", "color": "red", "reg": 134884 } ], "benz": [ { "car": "benz", "color": "red", "reg": 134444 } ] }
If you ever need to group by a computed key instead of a direct property (like grouping by uppercase car names), you can replace the "car" string with an expression (e.g., $uppercase(car)), but for your specific use case, the simple property selector works perfectly.
内容的提问来源于stack exchange,提问作者ARUN KUMAR
相关产品推荐
相关产品推荐

