Skip to content

Feature request: Membership operator (probably called in) #2322

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
kelvinlamwh opened this issue Mar 13, 2025 · 2 comments
Open

Feature request: Membership operator (probably called in) #2322

kelvinlamwh opened this issue Mar 13, 2025 · 2 comments

Comments

@kelvinlamwh
Copy link

Please describe your feature request.
Inverse operator of contains, probably called in or something alike?

Describe the solution you'd like
If we have data1.yml like:
(please keep to around 10 lines )

- {item: 'Pizza', type: 'Food'}
- {item: 'Pasta', type: 'Food'}
- {item: 'Rose', type: 'Flower'}
- {item: 'Tulip', type: 'Flower'}
- {item: 'Hammer', type: 'Tool'}
- {item: 'Screwdriver', type: 'Tool'}

And we run a command:

yq 'filter(.type | in(["Tool", "Food"]))' data1.yml

it could output

- {item: 'Pizza', type: 'Food'}
- {item: 'Pasta', type: 'Food'}
- {item: 'Hammer', type: 'Tool'}
- {item: 'Screwdriver', type: 'Tool'}

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

yq 'filter(.type as $el | ["Tool", "Food"] | contains([$el]))' data1.yml

Additional context
jq also has the in operator

@fearphage
Copy link

fearphage commented Mar 18, 2025

@kelvinlamwh Here are a few alternative implementations to get the same answer:

yq 'filter((["Tool", "Food"] - [.type] | length) < 2)' data1.yml

yq 'filter(.type | test("^(Tool|Food)$"))' data1.yml

The first one using subtract is definitely the oddest one. If we could define custom functions, that would be the definition of your in operator.

  1. Get the length of the input array
  2. Subtract the sequence of the lookup value
  3. If the sequence length has changed, it was found

IF we could define custom functions, I would codify the above steps as:

def in($array; $item):
  ($array | length) as $length | ($array - [$item] | length) < $length

I think the operator would be very welcome personally.

@mikefarah
Copy link
Owner

Adding a in operator makes sense to me as well. Note that jq defines is as the inverse of has not contains (which is a little looser) - yq should do the same to maintain consistency.

Happy to take a PR for this - otherwise I'll get to it when I can :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants