Group data from CSV file

It would be simpler if your data were in JSON, TOML, or YAML format, but if you’re stuck with CSV…

foo.csv

name,type
Felix,cat
Spot,dog
Rover,dog

template

{{/* Wrangle the CSV into a slice of objects. */}}
{{ $csv := getCSV "," "foo.csv" }}
{{ $cols := index $csv 0 }}
{{ $data := slice }}
{{ range $k, $v := $csv }}
  {{ if $k }}
    {{ $m := dict }}
    {{ range seq 0 (sub (len $cols) 1) }}
      {{ $m = merge $m (dict (index $cols .) (index $v .)) }}
    {{ end }}
    {{ $data = $data | append $m }}
  {{ end }}
{{ end }}

{{/* Build unique, sorted slice of types. */}}
{{ $types := slice }}
{{ range $data }}
  {{ $types = $types | append .type }}
{{ end }}
{{ $types = $types | uniq | sort }}

{{/* Display the grouped data. */}}
<ul>
  {{ range $types }}
    <li>
      {{ . }}
      <ul>
        {{ range where $data "type" . }}
          <li>{{ .name }}</li>
        {{ end }}
      </ul>
    </li>
  {{ end }}
</ul>

result

image

1 Like