-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

6
  • I recommend taking care of the comas before trying to render the string in DOM Commented Jul 26, 2021 at 10:26
  • @Bravo Thats not working. Comma not inserted. Commented Jul 26, 2021 at 10:26
  • 1
    yeah, because there's a LOT more wrong ... instead of that template, just use {{category.sub_category.map(({subcategory_name}) => subcategory_name).join(', ')}} Commented Jul 26, 2021 at 10:28
  • This is the most elegant, use CSS: stackoverflow.com/a/42130196/295783 Commented Jul 26, 2021 at 10:30
  • 1
    and yet, @mplungjan, you can see the criticisms of that solution are valid to a degree Commented Jul 26, 2021 at 10:31

2 Answers 2

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(', '); } } 
Sign up to request clarification or add additional context in comments.

3 Comments

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
Cannot read property 'sub_category' of undefined when use computed.
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
-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.

3 Comments

Not working. I've tried that many times
@SeadLab Can you please check into the updated answer I added a screenshot. I hope this is enough to prove that my solution will work
That's not what I mean. It's different. Please check the right answer above!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.