diff --git a/README.md b/README.md index 2f0acd4..9fbe3da 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1191 TILs and counting..._ +_1192 TILs and counting..._ --- @@ -28,6 +28,7 @@ _1191 TILs and counting..._ * [Git](#git) * [GitHub Actions](#github-actions) * [Go](#go) +* [GROQ](#groq) * [Heroku](#heroku) * [HTML](#html) * [HTTP](#http) @@ -336,6 +337,10 @@ _1191 TILs and counting..._ - [Sleep For A Duration](go/sleep-for-a-duration.md) - [Upgrading From An Older Version On Mac](go/upgrading-from-an-older-version-on-mac.md) +### GROQ + +- [Grab Values From An Array Of References](groq/grab-values-from-an-array-of-references.md) + ### Heroku - [Deploy A Review App To A Different Stack](heroku/deploy-a-review-app-to-a-different-stack.md) diff --git a/groq/grab-values-from-an-array-of-references.md b/groq/grab-values-from-an-array-of-references.md new file mode 100644 index 0000000..a13e0b1 --- /dev/null +++ b/groq/grab-values-from-an-array-of-references.md @@ -0,0 +1,29 @@ +# Grab Values From An Array Of References + +Let's say we have a `post` object in our schema. A `post` can have an array of +references to `tags` telling you what topics the post covers. Each `tag` has a +slug and we want to get the `string` value for each slug. + +Let's say we are interested in the post with `_id` of `123`. + +Here is how we can achieve that with a `groq` query: + +```groq +*[ + _type == 'post' && _id == 123 +]{ + 'tags': tags[]->slug.current +}.tags + +=> ["javascript", "react-js"] +``` + +If the schema was such that each `post` just had a single tag reference, then +you could write the chain of references as `tag->slug.current`. Because it is +an array of references, we need the `[]` to declare that we want each value. + +The `->` operator follows the reference. Otherwise we'd just have access to the +`_ref` and `_type` values. + +The final `.tags` unnests the `tags` value we gathered into an object. Then the +result is just the array of slug values.