79573936

Date: 2025-04-14 20:09:56
Score: 0.5
Natty:
Report link

Below is one standard solution using jq’s built‐in grouping and transformation functions:
jq 'group_by(.a)[] | { a: .[0].a, count: map(.b | length) | add }'

Result (the output is an object with each unique a as a key and the total count of b entries as the value):

{
  "foo": 3,
  "bar": 0
}

How It Works

  1. Grouping by a:
    The command starts with:

    jq group_by(.a)[] 
    

    This groups all objects in the array that share the same a value into subarrays. Each subarray contains all objects with that same a.

  2. Extracting the Unique Key:
    For each group (which is an array), the expression:

    jq .[0].a 
    

    extracts the common a value from the first item. Since all objects in the group have the same a, this is safe.

  3. Counting Entries in b:
    The expression:

    jq map(.b | length) | add 
    

    takes the current group (an array of objects), maps each object to the length of its .b array, and then sums them with add. This sum represents the total count of all entries in b for that particular a.

  4. Building the Output Object:
    The { a: .[0].a, count: ... } syntax creates an object with two fields: the a value and the computed count.

In the future if you'd like to use jq in any JetBrains IDE, please check out my plugin: https://plugins.jetbrains.com/plugin/23360-jqexpress

Reasons:
  • Contains signature (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: jqExpress