See how we built our intranet. Live + Q&A, June 30

How to loop over Arrays of different Objects in Sanity?

2 repliesLast updated: Nov 29, 2025

Speaking of structure and patterns – how do you all loop over your Arrays of different Objects? I had come up with a much messier version of this in the past. But then was thinking about it like how
serializers
works and think it’s much cleaner.
AI Update

Great question! The serializer pattern is indeed a really clean approach for handling arrays of different object types. It's the same pattern that makes Portable Text rendering so elegant, and it works beautifully for any array with mixed types.

Here's the basic pattern that mirrors how serializers work for Portable Text:

// Define your type handlers
const typeHandlers = {
  youTube: (item) => <YouTubeEmbed {...item} />,
  blogPost: (item) => <BlogPostCard {...item} />,
  imageGallery: (item) => <Gallery images={item.images} />,
  // ... more types
}

// Loop through your array
{items.map((item) => {
  const Handler = typeHandlers[item._type]
  return Handler ? (
    <Handler key={item._key} {...item} />
  ) : null
})}

Or if you prefer a more functional approach:

const renderItem = (item) => {
  switch(item._type) {
    case 'youTube':
      return <YouTubeEmbed {...item} />
    case 'blogPost':
      return <BlogPostCard {...item} />
    case 'imageGallery':
      return <Gallery images={item.images} />
    default:
      return null
  }
}

{items.map((item) => (
  <Fragment key={item._key}>
    {renderItem(item)}
  </Fragment>
))}

The key benefits of this pattern:

This works great with Sanity's array fields that support multiple member types, where you might have a schema like:

{
  name: 'content',
  type: 'array',
  of: [
    {type: 'youTube'},
    {type: 'blogPost'},
    {type: 'imageGallery'}
  ]
}

The _type property on each array item tells you which handler to use, and the _key property (automatically added by Sanity) gives you a stable key for React's reconciliation.

Much cleaner than a bunch of nested conditionals!

Show original thread
2 replies

Was this answer helpful?

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Related contributions