Structured Content 101: Find out how to make your content work harder (without your team working harder) →

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