Search code examples
open-policy-agentrego

Take every item in list that starts with x and put it in a new list - Rego


list := ["a:aqsdf", "a:asdf", "b:gfs", "b:sdf", "a:adfd", "b:asdfd"]

I want the new list to only include items that start with 'a': ["a:aqsdf", "a:asdf", "a:adfd"]

I've tried working with sets with no success. This would be a breeze in python but can't seem to wrap my head around rego. I can turn it into a set but not sure how to squeeze in an if statement(startswith(list[_], "a") == true)


Solution

  • One way to do this is with an array comprehension and the startswith builtin function:

    [ x | x := list[_]; startswith(x, "a")]
    

    Playground example: https://play.openpolicyagent.org/p/8mQYYvUL2h

    This is essentially saying to define a new array containing the value of x if the rule body is true. The rule body for the comprehension is in turn iterating over all indicies of list for values of x, and will be true when the value of x starts with "a".

    References: