Search code examples
jsonjqremove-if

Using jq to remove items from an array based on values elsewhere in the input


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


Solution

  • Here's a concise and efficient solution:

    .update.toRemove as $rm
    | .source
    | .items |= map( select(.id | IN($rm[]) | not))