Home > Back-end >  How do you loop thru array and create glossary list with categories
How do you loop thru array and create glossary list with categories

Time:03-10

I have an array with a list of definitions. Using Vue.js, what is the best way to loop through that array and create a glossary list with letters as the categories?

Desired Output:

A

  • Aterm: A definition of aterm

B

  • Bterm: A definition of bterm

C

  • Cterm: A definition of cterm
  • Cterm: A definition of cterm
  • Cterm: A definition of cterm

Y

  • Yterm: A definition of yterm
  • Yterm: A definition of yterm

Z

  • Zterm: A definition of zterm

Codepen: https://codepen.io/mrg-tking/pen/WNXqVLp

<div id="app" >
  <div v-for="(item, index) in fields" :key="index">
    <span>{{ item.Term.charAt(0) }}
    <h3>{{ item.Term }}</h3>
    <p>{{ item.Definition }}</p>
  </div>
</div>

var app = new Vue({
  el: '#app',
  data: {
    parentMessage: 'Parent',
    fields: [
      { Term: 'Aterm', Definition: 'A definition for aterm' },
      { Term: 'Bterm', Definition: 'A definition for bterm' },
      { Term: 'Cterm', Definition: 'A definition for cterm' },
      { Term: 'Cterm', Definition: 'A definition for cterm' },
      { Term: 'Cterm', Definition: 'A definition for cterm' },
      { Term: 'Mterm', Definition: 'A definition for mterm' },
      { Term: 'Yterm', Definition: 'A definition for yterm' },
      { Term: 'Yterm', Definition: 'A definition for yterm' },
      { Term: 'Zterm', Definition: 'A definition for zterm' }
    ]
  },
  methods: {
    // do something
  }
})

CodePudding user response:

Create a computed property that groups the fields by letter (using Array.prototype.reduce() on this.fields[]):

new Vue({
  computed: {
    fieldsByTerm() {
      return this.fields.reduce((p, field) => {
        const letter = field.Term.at(0).toUpperCase() // use uppercase first letter
        p[letter] ??= []      // create array for this letter if needed
        p[letter].push(field) // add term to array
        return p              // return updated object
      }, {})
    }
  },
})

Then iterate the computed object with v-for:

<div id="app" >
  <div v-for="(fields, letter) in fieldsByTerm" :key="letter">
    <h3>{{ letter }}</h3>
    <ul>
      <li v-for="item in fields" :key="item.Term">
        <span>{{ item.Term }}:</span>
        <span>{{ item.Definition }}</span>
      </li>
    </ul>
  </div>
</div>

demo

CodePudding user response:

So, I'll benefit lodash to solve the problem.

First, you need to import lodash. It is a powerful tool for manipulating data structure based on my experience.

import * as _ from "https://cdn.skypack.dev/[email protected]";

You need to add this code:

  • Related