<p>Working with <a href="https://www.openpolicyagent.org/docs/latest/policy-language/" rel="nofollow noreferrer">Rego</a>, the <a href="https://www.openpolicyagent.org/" rel="nofollow noreferrer">Open Policy Agent</a> (OPA) &quot;rules&quot; language, and given the following data:</p>
<pre><code>{
    &quot;x-foo&quot;: &quot;a&quot;,
    &quot;x-bar&quot;: &quot;b&quot;,
    &quot;y-foo&quot;: &quot;c&quot;,
    &quot;y-bar&quot;: &quot;d&quot;
}
</code></pre>
<p>what is the correct Rego expression(s) or statement(s) to get just the keys that start with &quot;x-&quot;? That is, I want an array of</p>
<pre><code>[ &quot;x-foo&quot;, &quot;x-bar&quot; ]
</code></pre>
<p>I know about the <code>startswith()</code> function, and I've tried various attempts at <a href="https://www.openpolicyagent.org/docs/latest/policy-language/#comprehensions" rel="nofollow noreferrer">comprehensions</a>, but no matter what I try I can't get it to work.</p>
<p>Any help would be much appreciated.</p>

asm2stacko
<p>This can be accomplished either by using a comprehension, like you suggest, or a partial rule that <a href="https://www.openpolicyagent.org/docs/latest/policy-language/#generating-sets" rel="nofollow noreferrer">generates a set</a>:</p>
<pre><code>x_foo_comprehension := [key | object[key]; startswith(key, &quot;x-&quot;)]

x_foo_rule[key] {
    object[key]
    startswith(key, &quot;x-&quot;)
}
</code></pre>
<p>Finally, if you need to take nested keys into account, you could use the walk built-in to traverse the object:</p>
<pre><code>x_foo_rule[key] {
    walk(object, [path, value])
    last := path[count(path) - 1]
    startswith(last, &quot;x-&quot;)
    key := concat(&quot;.&quot;, path)
}

# x_foo_rule == {
#     &quot;x-bar&quot;,
#     &quot;x-foo&quot;,
#     &quot;y-bar.x-bar&quot;,
#     &quot;y-bar.x-foo&quot;
# ]
</code></pre>
