[Vuejs]-Display data set based on string content using vuejs

0👍

Create a computed property that uses Array.prototype.filter on the todos[]. The callback to filter() receives each array item, and returns true if the item should be in the result. In this callback, you can check if each item contains the leading characters (before the underscore) in the search string (LA in your example):

export default {
  computed: {
    computedTodos() {
      const searchLetters = this.Name.split('_')[0].split('')   /* get characters of first part of string before underscore */
                                     .filter(x => /\w/.test(x)) /* keep only letters */
      return this.todos.filter(item => {
        /* check if each letter appears in order within the item's name */
        let i = 0
        return searchLetters.every(letter => {
          i = item.Name.indexOf(letter, i)
          return i > -1
        })
      })
    }
  }
}

Then update the template to use the computed prop instead of todos[]:

<!-- <li v-for="todo in todos"> -->
<li v-for="todo in computedTodos">
new Vue({
  el: "#app",
  data: {
  Name:"LA_123_cc",
    todos: [{"Name":"Library Arts","Identifier":"6774","Code":"AACSF-LA","Subjects":["LA_","AEL","APC","GAP","FAC","GLM","GS","MPT","PRO","WNM"]},
   {"Name":"Violin Dance","Identifier":"6169","Code":"Avvv-VA","Subjects":["VA","VL","VPC","AAP","YAC","XLM","GXS","XPT","IRO","CNM"]} 
    
    ]
  },
  computed: {
    computedTodos() {
      const searchLetters = this.Name.split('_')[0].split('').filter(x => /\w/.test(x))
      return this.todos.filter(item => {
        let i = 0
        return searchLetters.every(letter => {
          i = item.Name.indexOf(letter, i)
          return i > -1
        })
      })
    }
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input v-model="Name">
  <h2>Name: {{Name}}</h2>
  <ol>
    <li v-for="todo in computedTodos">
    Name: {{todo.Name}} <br>
    Department: {{todo.Code}}<br>
    Identifier: {{todo.Identifier}}
    </li>
  </ol>
</div>

Leave a comment