✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Group documents by year

By Rune Botten

How to group documents by their publishedAt year using the Structure Builder API


import S from '@sanity/desk-tool/structure-builder'
import client from 'part:@sanity/base/client'

export default () =>
        .title('Posts by year')
        .child(() => {
          const type = 'post'
          return client.fetch('* [_type == $type && defined(publishedAt)] {_id, _type, publishedAt}', {
            .then(docs => {
              // Create a map of years
              const years = {}
              docs.forEach(d => {
                const date = new Date(d.publishedAt)
                const year = date.getFullYear()
                if (!years[year]) { years[year] = [] }
              return S.list()
                .title('Posts by year')
                  Object.keys(years).map(year => {
                    return S.listItem()
                          .title(`Posts from ${year}`)
                          .filter(`_id in $ids`)
                          .params({ ids: years[year] })

This example shows how you can use the Structure Builder API to group documents by year based on a date field (like publishedAt).


Other schemas by author

Custom default desk pane

An example of overriding the default Studio Desk pane to add some business logic around menu items.

Rune Botten
Go to Custom default desk pane