This is a followup to question list of occurences of references. In the MWE below the index lists the Goals in alphabetic order where numeric is needed for the second token:

The solution I found (on SE - sorry I lost the link) for the chapter and section numbers for the subsidiary indexing doesn't seem to work for the main headings. I tried a few others, to no avail.
Edit: the solution to convert outcome of reference to regular number looks as if it ought to work but I tried something like that and it failed.
\documentclass[12pt]{book}
\usepackage{amsthm}
\usepackage{environ}
\usepackage{imakeidx}
\usepackage{refcount}
\usepackage{hyperref}
\makeindex[intoc]
\makeindex[name=goals,title=Goal References,columns=1,intoc]
\newcommand{\gref}[1]{%
[Goal~\ref{goal:#1}]
\index[goals]{Goal~\getrefnumber{goal:#1}!Section
\ifnum\value{chapter}<10 0\fi\arabic{chapter}.%
\ifnum\value{section}<10 0\fi\arabic{section}}
}
\makeatletter
\newcommand\l@goal[1]{%
\addpenalty{\@highpenalty}%
\vskip \z@ \@plus \p@
\begingroup
\parindent\z@
\rightskip\@pnumwidth
\parfillskip-\@pnumwidth
\leavevmode #1\nobreak\hfil\nobreak\null\par
\penalty\@highpenalty
\endgroup}
\newcommand{\egregaddtocontents}[1]{%
\addtocontents{toc}{\protect\l@goal{#1}}}
% arrange goal numbering by chapter
\newtheorem{Goal}{Goal}[chapter]
% define a shorthand to be able to get at \BODY with \expandafter
\newcommand\indexgoal[1]{\goalindex[goals]{Goal~\theGoal! #1}}
% save a copy of \index
\let\goalindex\index
\NewEnviron{goal}[1]{%
\begin{Goal}
\label{goal:#1}%
% here we neutralize \index so that it won't do damages
\begingroup
\renewcommand\index[2][]{}%
% but the main command uses \goalindex, so it's safe
\expandafter\indexgoal\expandafter{\BODY}%
\egregaddtocontents{\BODY}
\endgroup
%{\em label:} #1 %comment in/out to restore/suppress printing label
\normalfont{}\noindent
\BODY
}
[\end{Goal}]
\makeatother
\newenvironment{goals}
{%
{\textbf Chapter goals:}
\egregaddtocontents{Chapter goals:}
}
{}
\begin{document}
\tableofcontents{}
\setcounter{chapter}{1}
\chapter{TWO}
\tracingmacros=1
\begin{goals}
\begin{goal}{twofirst}
learn more \LaTeX
\end{goal}
\end{goals}
\tracingmacros=0
\begin{goal}{twosecond}
spend time on content, not \LaTeX
\end{goal}
\section{two-one}
stuff\index{stuff}
Reference to a chapter 11 goal: \gref{elevenfirst}
\setcounter{chapter}{10}
\chapter{ELEVEN}
\begin{goal}{elevenfirst}
have fun in any case\index{fun}
\end{goal}
Chapter contents here, referring to some goals:
\setcounter{section}{1}
\section{whatever}
Reference to a chapter 2 goal: \gref{twosecond}
Reference to a chapter 11 goal: \gref{elevenfirst}
\setcounter{section}{10}
\section{another}
Second reference to a chapter 2 goal: \gref{twofirst}
\printindex[goals]
\printindex
\end{document}
