What does cake have to do with content operations? šŸ° šŸ‘€ Find out in our Spring Release... →

How to get the number of nested/children components in a GROQ query.

3 replies
Last updated: Jan 19, 2024
hello all šŸ‘‹ I have the following GROQ: I’m retrieving a list of components as ā€˜items’. Now I need the number of nested/children components each parent component has. How can I get the number of each component’s children/subpages? I was trying to obtain this number inside ā€˜children’.

{
            template,
            layout_library {
                hero_title,
                components_section_title,
                'items': *[_type == 'components' && layout_components.is_parent == true] | order(title asc){
                    title,
                    _id,
                    slug,
                    layout_components {
                      component_image${imageQuery},
                    }
                },
                'children': *[_type == 'components' && layout_components.is_parent == false] | order(title asc){
                    ???
                },
            },
        }
Jan 18, 2024, 6:20 PM
'children': *[count(_type == 'components' && layout_components.is_parent == false)]
Jan 18, 2024, 6:46 PM
thanks
user E
! but this wouldn’t work as I don’t need just one number.
Let me explain this a little bit more. I’ve got a Library page for a Design system where I’m looping main components like Button and Accordion. Button has 3 types of buttons/subpages: button/button-01, button/button-02 and button/button-03.

In Library, I’m looping the components that are parent pages and show the info of them. In this case the title for Button and a description. And then, just under the the description it says ā€œ3 button types availableā€. how do I get the 3 for button, the X for accordion and other numbers for other components?
Jan 19, 2024, 8:58 AM
āœ… fixed it this way:
'items': *[_type == 'components' && layout_components.is_parent == true] | order(title asc){
                    title,
                    _id,
                    slug,
                    'total': count(*[_type == 'components' && parent_component == ^.slug.current]),
                    
                },
Jan 19, 2024, 9:52 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?