Go Behind the Experience to see how Tecovas brings the West to life with Sanity 🤠 July 18th

Troubleshooting GROQ query for generating author initials in Sanity

6 replies
Last updated: Jun 28, 2024
Why doesn't this work?
"initials": _firstName_[0]
+ _lastName_[0]
😞
Jun 23, 2024, 4:52 AM
Work where? is this a Groq query? What does your schema look like?
Jun 23, 2024, 11:29 AM
*[_type == "author"] {
  name,
  "avatarUrl": select(
    defined(image) => image.asset->url,
    "<https://ui-avatars.com/api/?name=>" + 
    coalesce(
      substr(firstName, 0, 1),
      ""
    ) + 
    coalesce(
      substr(lastName, 0, 1),
      ""
    ) +
    "&background=random"
  )
}
Jun 23, 2024, 3:20 PM
Assuming a groq query and not javasript
Jun 23, 2024, 3:21 PM
likely need to do
firstname.split()[0] + lasname.split()[0]
to turn string into array first.
Jun 23, 2024, 3:26 PM
Yes a groq query. We can do that in JS so I just thought it would be nice and simple here, but instead my projection looks like this:
"initials": array::join(string::split(firstName, "")[0...1], "") + array::join(string::split(lastName, "")[0...1], ""),
This works, but it feels icky.
Jun 24, 2024, 4:06 PM
*[_type=="vendor"] {
  "raw" : string::split(vendorName,""),
  "lowercase" : string::split(lower(vendorName),""),
}{
  "initials" : raw[!(@ in ^.lowercase)]
}

// leads to
initials:[…] 2 items
  0:J
  1:B
Is another approach. A different version of this can be a good way to capture duplicates, comparing a regular array and an array::unique() array and accounting for the difference.
Jun 28, 2024, 5:18 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?