-2

I want to remove comma in the last element in Vue. But I dont know how to do that because the index of the last element is unknown.

<td v-if="category.sub_category.length > 0"> 
                      <template v-for="cat in category.sub_category">
                        {{ addComma(cat.subcategory_name) }}
                      </template>
                    </td>

addComma(subCat) {
  let elements = [];
  elements.push(subCat);
  console.log(elements);
  
  if (elements != ""){
    elements += ", ";
  }

  return elements;
},

And this is the result of console.log(elements) above.

enter image description here

And this is the result of all code above

enter image description here

Sead Lab
  • 191
  • 3
  • 20

2 Answers2

1

This should work

<td v-if="category.sub_category.length > 0">
      {{category.sub_category.map(({subcategory_name}) => subcategory_name).join(', ')}}
</td>

I'd be tempted to move it to a computed though - keeps markup clean

<td v-if="category.sub_category.length > 0">
      {{subcats}}
</td>


computed: {
  subcats() {
    return this.category.sub_category.map(({subcategory_name}) => subcategory_name).join(', ');
  }
}
Bravo
  • 6,022
  • 1
  • 10
  • 15
  • I'd be tempted to move that into a computed or a method, personally - I like to leave the markup relatively clean - the question was closed as I posted, so, not sure I can update to show what I mean – Bravo Jul 26 '21 at 10:32
  • `Cannot read property 'sub_category' of undefined` when use computed. – Sead Lab Jul 26 '21 at 10:44
  • perhaps because at some point, this.category is empty .... @SeadLab - maybe don't use that method then - I've been away from vuejs for a while and there's probably things about your data that are not clear to me – Bravo Jul 26 '21 at 10:48
-3
elements.join(',')

You don't need to create a function for this just use it inside the Vue tag like this

{{elements.join(',')}}

enter image description here

Please check in image. I posted answer after checking.

Muhammad Atif Akram
  • 1,204
  • 1
  • 4
  • 12