Konstantin
Konstantin

Reputation: 67

JQ: Finding array index of object with specific attribute value

I have the following:

{"arr":[{"Name":"web"},{"Name":"app"}]}

I need to find out the array index of all array objects that do not have "app" in the attribute "Name".

I've tried to use a combination of "select" and "keys" but this does not work:

jq '.arr[] | select(.Name != "app") | keys'

Upvotes: 2

Views: 776

Answers (2)

peak
peak

Reputation: 116770

Here's one of many possibilities:

.arr | range(0;length) as $i | select(.[$i].Name != "app") | $i

And slightly more briefly but less efficiently:

.arr | to_entries[] | select(.value.Name != "app") | .key

And if you are itching to use a for-style loop, or if you want something to think about:

foreach .arr[] as $o (-1; .+1; select($o.Name != "app"))

Upvotes: 4

jq170727
jq170727

Reputation: 14665

Here is a solution which uses tostream.

      tostream
    | if   .[0][-1] == "Name" and .[1] == "app"
      then .[0][-2]
      else  empty
      end

Upvotes: 0

Related Questions