javascriptvue.jsvuejs2vue-componentvue-filter

Vue for loop data format change


I have some data being sent in for students and their bank account balance. In vue I am using v-for to loop through the data and put it into a table.

The issue I am having is I can't figure out how to change the formate when the loop gets to there bank account balance. I would like it to formate with "," in the right locations and put a $ on the front.

I have made a filter that does all of this, but I can not figure out how to apply it to only the "bank" id name within my data.

gridData: [
      { id: 1, first_name: 'fname1', last_name: 'lname1', student_number:'1111', bank:100.01},
      { id: 2, first_name: 'fname2', last_name: 'lname2', student_number:'2222', bank:100.02},
      { id: 3, first_name: 'fname3', last_name: 'lname3', student_number:'3333', bank:100.03},
      { id: 4, first_name: 'fname4', last_name: 'lname4', student_number:'4444', bank:100.04},
    ]

Then I am adding all the data with these two lines. I have some other functions that allow the user to type anything into the search box and it will filter it based on what is in the search box.

<tr v-for="entry in filteredData" :key="entry.id">
            <td v-for="key in columnID" :key="key.id"> {{entry[key]}}</td>

And the filters I have added to change the format of the data looks like:

  filters: {
capitalize: function (str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
},
toUSD: function (value) {
  if (typeof value !== "number") {
      return value;
  }
  var formatter = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 0
  });
  return formatter.format(value);
}

},

If I change it to:

<tr v-for="entry in filteredData" :key="entry.id">
        <td v-for="key in columnID" :key="key.id"> {{entry[key] | toUSD}}</td>

Then it is obviously applied to all of the entry keys. My question is how can I apply that filter to only the "bank" entry key?

Any help is greatly appreciated.


Solution

  • You can use a v-if/else on the key:

    <td v-for="key in columnID" :key="key.id"> 
        <span v-if="key === 'bank'">{{entry[key] | toUSD}} </span>
        <span v-else> {{ entry[key] }} </span>
    </td>