Skip to content

Accessing the index of current array element within "unnest" subquery #5182

@philrz

Description

@philrz

In a recent community Slack thread, a user was manipulating an array in an over scope in a way that required knowing the index of each value. I responded with an example that achieved this using count(), to which @mattnibs commented:

I kind of think having to using streaming count() for this case here is kind of a hack and that you should be able to access the index of the current element from within the over scope. The hard part is coming up with a elegant way of doing this...

Details

Repro is with Zed commit 6e61673.

The specific question posed by the user:

is there a way to change this: ["a","b"] to [{"a":1},{"b":2}]based on the index location of each item? (for any length array...)

My response:

$ zq -version
Version: v1.16.0-15-g6e61673c

$ echo '["a","b","c"]' | zq -j '
over this => (yield [{key:this,value:count()}] | unflatten(this))
| collect(this)
' -
[{"a":1},{"b":2},{"c":3}]

The user noted how Ruby provides this via each_with_index in Ruby.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions