How to access nested navigationItemUrl text property in Sanity query map?
0:{…} 8 properties
_createdAt:2022-12-07T23:19:09Z
_id:navigation
_rev:Bp455s9rtQ49wRO6vY4ZPz
_type:navigation
_updatedAt:2022-12-08T21:58:33Z
items:[…] 1 item
0:{…} 4 properties
_key:7f41faf793a8
_type:navigationItem
navigationItemUrl:{…} 2 properties
_type:link
internalLink:{…} 2 properties
text:login
navId:{…} 2 properties
_type:slug
current:mainMenu
title:Browse{navs.map((navs: any) => (
<div key={navs._id}>{navs.title}</div>
))}How might I go about this?
This is a JavaScript/TypeScript data traversal question rather than a Sanity-specific issue. Looking at your data structure, you need to access nested properties within the items array.
Based on your data structure, navigationItemUrl.internalLink contains the text property you want. Here's how to access it:
{navs.map((nav: any) => (
<div key={nav._id}>
<h3>{nav.title}</h3>
{nav.items?.map((item: any) => (
<div key={item._key}>
{item.navigationItemUrl?.internalLink?.text}
</div>
))}
</div>
))}The key points:
- You need to map over
nav.items(the array of navigation items) - Each item has a
navigationItemUrlobject - Inside that is
internalLinkwhich contains yourtextproperty - Use optional chaining (
?.) to safely access nested properties - Use
item._keyas the key since each navigation item has that unique identifier
If you want to create actual links, you might do something like:
{navs.map((nav: any) => (
<nav key={nav._id}>
<h3>{nav.title}</h3>
<ul>
{nav.items?.map((item: any) => (
<li key={item._key}>
<a href={item.navigationItemUrl?.internalLink?.text}>
{item.text || item.navigationItemUrl?.internalLink?.text}
</a>
</li>
))}
</ul>
</nav>
))}TypeScript tip: Instead of using any, consider using Sanity TypeGen to generate proper types for your schema. This would give you autocomplete and type safety for these nested structures, making it much easier to work with complex data like this navigation structure.
Show original thread7 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.