1

I have a table generated using an array of objects. I am having a hard time figuring out how to use computed properties to filter the array of objects. I am using VuE.js. I'm not sure how to properly use the filter() in my computed properties to filter the table.

new Vue({
  el:"#app",
  data: () => ({
    search:'',
    programs: [],
    editableKeys: ['date', 'company', 'funding', 'funded', 'recruit', 'program'],
  }),
  created () {
    this.getPrograms();
  },
  methods: {
    getPrograms() {
     axios.get("https://my-json-server.typicode.com/isogunro/jsondb/Programs").then(response => {
       this.programs = response.data.map(program => ({
           ...program,
           isReadOnly: true,
            dropDowns: ["Apple","Google"]
       }));
      }).catch(error => {
       console.log(error);
      });
    },
    editItem (program) {
      program.isReadOnly = false
    },
    saveItem (program) {
      program.isReadOnly = true
      console.log(program)
      alert("New Value: "+program.company)
      alert("Previous Value: "+program.company)
    },
    bgColor (program) {
      return program.funded === program.funding ? 'yellow' : 'white'
    },
    formatDate(program){
      var formatL = moment.localeData().longDateFormat('L');
      var format2digitYear = formatL.replace(/YYYY/g,'YY');
      return moment(program.Date).format(format2digitYear);
    },
    updateField(program){
      console.log(program)
      alert(program)
    }
  },
  computed: {
    searchContents(){
      this.programs.filter(this.search === )//??? not sure how to filter correctly
    }
  }
})

Here's the pen

OLA
  • 861
  • 2
  • 11
  • 23
  • Does this answer your question? [How to filter an array in javascript?](https://stackoverflow.com/questions/45916135/how-to-filter-an-array-in-javascript) – yuriy636 Nov 30 '19 at 19:58

1 Answers1

5

Computed properties have to return a value, and you can use it as same as data and props. So what you need to do is return the result of the filter. For the case with no search option, you can return raw programs without the filter.

The computed property will be like this: (if you filter the programs by it's funding attribute.)

computed: {
  searchContents(){
    if (this.search === '') {
      return this.programs
    }

    return this.programs.filter(x => this.search === x.funding)
  }
}

Then you can use that computed property in v-for:

  <tr v-for="(program, index) in searchContents">
shotasenga
  • 939
  • 7
  • 17
  • I made the change but nothing happens. https://codepen.io/isogunro/pen/bGGrWZG?editors=1011 – OLA Dec 01 '19 at 00:49
  • It looks working. When you type `NO` on the search box, the table shows only the data which has `NO` as the value of `funding`. – shotasenga Dec 01 '19 at 00:54
  • Oh...I was expecting a gradual search..so if I type ```N```, I would see anything starting with ```N``` – OLA Dec 01 '19 at 00:57