Vue js Capitalize each word of a string value in an array of objects :To capitalize each word of a string value in an array of objects using Vue.js, you can use a combination of JavaScript’s map()
method and the toUpperCase()
method. First, use the map()
method to iterate over each object in the array. Then, access the string value using the appropriate key, split the string into an array of words using the split()
method, use the map()
method to iterate over each word in the array and capitalize the first letter of each word using the toUpperCase()
method, and finally join the words back together using the join()
method. This process will capitalize each word in the string value of each object in the array.
How can we capitalize each word of a string value in an array of objects using Vue js?
The capitalizeWords
method takes a string as a parameter and returns a new string with each word capitalized. The method does this by first converting the entire string to lowercase using toLowerCase()
, splitting the string into an array of words using split(" ")
, capitalizing the first letter of each word using map()
, and then joining the words back together into a single string using join(" ")
.
In the template, the capitalizeWords
method is called on the name
property of each person
object using {{ capitalizeWords(person.name) }}
, which displays the capitalized name in each list item.
So, in summary, your existing code is already doing what you want – capitalizing each word of a string value in an array of objects using Vue j
Vue js Capitalize each word of a string value in an array of objects Example
<div id="app">
<ul>
<li v-for="(person, index) in people" :key="index">
{{ capitalizeWords(person.name) }}
</li>
</ul>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
people: [
{ name: "john doe", age: 25 },
{ name: "jane smith", age: 30 },
{ name: "jimmy carter", age: 40 },
],
};
},
methods: {
capitalizeWords(str) {
return str
.toLowerCase()
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
},
},
});
</script>