Home > Back-end >  Merging property values of objects with common key with jq
Merging property values of objects with common key with jq

Time:03-02

I have an array of objects with 2 properties, say "key" and "value":

[
   {key: 1, value: a}, 
   {key: 2, value: b}, 
   {key: 1, value: c}
]

Now, I would like to merge the values of the "value" properties of objects with the same "key" property value. That is the previous array is transformed into:

[
   {key: 1, value: [a, c]}, 
   {key: 2, value: [b]}
]

I tried something like:

$ echo '[{"key": "1", "val": "a"}, {"key": "2", "val": "b"}, {"key": "1", "val": "c"}]' | jq '. | group_by(.["key"]) | .[] | reduce .[] as $in ({"val": []}; {"key": $in.key, "val":  [$in.val]   .["val"]})'

But it triggers a jq syntax error and I have no idea why. I am stuck.

Any idea ?

Thanks

B

CodePudding user response:

Your approach using reduce could be sanitized to

jq 'group_by(.["key"]) | .[] |= reduce .[] as $in (
  {value: []}; .key = $in.key | .value  = [$in.value]
)'
[
  {
    "value": [
      "a",
      "c"
    ],
    "key": 1
  },
  {
    "value": [
      "b"
    ],
    "key": 2
  }
]

Demo

Another approach using map would be

jq 'group_by(.key) | map({key: .[0].key, value: map(.value)})'
[
  {
    "key": 1,
    "value": [
      "a",
      "c"
    ]
  },
  {
    "key": 2,
    "value": [
      "b"
    ]
  }
]

Demo

  • Related