0 day streak
javascript / beginner
Snippet

Formatting Prices in a Product List with Array Map in Vue

The Array.prototype.map() method transforms each element in an array and returns a brand-new array with the updated values. Inside a Vue computed property, using .map() allows you to create formatted presentation data (such as currency strings) without mutating the original reactive source data.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
import { ref, computed } from 'vue';
const products = ref([
{ id: 1, name: 'Book', price: 12.5 },
{ id: 2, name: 'Pen', price: 1.99 }
]);
const formattedProducts = computed(() => {
return products.value.map(item => ({
...item,
formattedPrice: `$${item.price.toFixed(2)}`
}));
});
vue
Breakdown
1
import { ref, computed } from 'vue';
Imports the reactive state primitives ref and computed from Vue.
2
const products = ref([
Declares a reactive array containing raw product data with numeric prices.
3
const formattedProducts = computed(() => {
Defines a computed property that automatically re-evaluates when products changes.
4
return products.value.map(item => ({
Iterates over every product using map to build a new transformed object.
5
...item,
Uses the spread operator to preserve existing product properties like id and name.
6
formattedPrice: `$${item.price.toFixed(2)}`
Formats the numeric price into a two-decimal string with a dollar prefix.