fe_alice
fe_alice

Reputation: 1

Combine lists by object key in JQ

I'd like to aggregate a list of objects like this:

[
  {"a": 1, "b": 2},
  {"a": 3, "b": 4}
]

To a single object with list values:

{
  "a": [1,3],
  "b": [2,4]
}

I've scoured the docs but I think I just don't know the term for what I'm trying to do. Any ideas?

Upvotes: 0

Views: 55

Answers (2)

jq170727
jq170727

Reputation: 14715

Here is another approach using reduce and to_entries:

reduce ( .[] | to_entries[] ) as {$key,$value} ({}; .[$key] += [$value]) 

Try it online!

Upvotes: 1

peak
peak

Reputation: 116957

A straightforward and efficient approach would be:

reduce .[] as $o ({};
  reduce ($o|keys_unsorted[]) as $k (.;
    .[$k] += [$o[$k]]))

Upvotes: 1

Related Questions