Loop Json data array and collect elements in groups

Hi, i have some data in list.json like so…

[ {
    "name": "item-1",
    "parent": "group-A"
 }, {
     "name": "item-2",
     "parent": "group-B"
  },{
     "name": "item-3",
      "parent": "group-A"
  },{
     "name": "item-4",
      "parent": "group-B"
}]

I want so group them in a nested list by parent, like so

<ul>
  <li>group-A 
    <ul>
      <li>item-1</li>
      <li>item-3</li>
    </ul>
  </li>
  <li>group-B 
    <ul>
      <li>item-2</li>
      <li>item-4</li>
    </ul>
  </li>
</ul>

I don’t know how many groups I have, and how many items, so I have to scan and collect the whole list in advance. My idea was to use Scratch for this, but that doesn’t work out:

This is called in a shortcode:

{{ $list = site.Data.list }}

{{ $s := newScratch }}
{{ range  $list }}
{{ $sb.Add .parent (slice .name) }}
{{ end }}

After that I have my final output loop, where I get an…

Error: range can’t iterate over Scratch:

<ul>
  {{ range $s }}
  <li>{{ . }} {{/* test me*/}}
    <ul>
      <li>item-1</li>
      <li>item-3</li>
    </ul>
  </li>
  {{ end }}
</ul>

Ive tested also this one, but that seemed not to have any add Methods:

{{ $s.SetInMap "test" .parent (slice .name) }}

What’s the best way to achieve this?

Happy new year and best regards :slight_smile:

{{/* Build uniq and sorted slice of group names. */}}
{{ $groups := slice }}
{{ range site.Data.list }}
  {{ $groups = $groups | append .parent }}
{{ end }}
{{ $groups = $groups | uniq | sort }}

{{/* Render the unordered list. */}}
{{ with $groups }}
  <ul>
    {{ range . }}
      <li>{{ . }}
        {{ with where site.Data.list "parent" . }}
          <ul>
            {{ range sort . "name" }}
              <li>{{ .name }}</li>
            {{ end }}
          </ul>
        {{ end }}
      </li>
    {{ end }}
  </ul>
{{ end }}
2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.