1

I'm new to jq and trying to wrap my head around doing a few things that I thought were going to be straightforward. Any ideas on how to improve this would be greatly appreciated.

Given this input:

{
    "source": {
        "items": [
            { "id": "aaa", "name": "this" },
            { "id": "bbb", "name": "that" },
            { "id": "ccc", "name": "the other" }
        ]
    },
    "update": {
        "toRemove": [
            "aaa",
            "ccc"
        ]
    }
}

I want this result:

{
    "items": [
        { "id": "bbb", "name": "that" }
    ]
}

This filter does the job but the variables lead me to believe there is a cleaner way.

. as $root | .source + { items: [.source.items[] | select(.id as $id | $root.update.toRemove | contains([$id]) | not)]}

Playground link if interested: https://jqplay.org/s/GpVJfbTO-Q

peak
  • 105,803
  • 17
  • 152
  • 177
user774031
  • 346
  • 3
  • 9

2 Answers2

2

Here's a concise and efficient solution:

.update.toRemove as $rm
| .source
| .items |= map( select(.id | IN($rm[]) | not))
peak
  • 105,803
  • 17
  • 152
  • 177
1

A little shorter version using inside instead of contains:

.update.toRemove as $temp |
 {items: [.source.items[] | select([.id] | inside($temp) | not)]}
Kamal
  • 2,384
  • 1
  • 13
  • 25