Transforming the String Values in an Array to Capitalize the First Letter of Each Word Using VueJS

After receiving an array of objects from an API call:

"data": [
  {
    "heading_one_of_the_table": 14,
     "total": 8
  },
  {
    "heading_one_of_the_table": 1,
    "total": 7
  },
  {
    "heading_one_of_the_table": 6,
    "total": 7
  }
]

I want to transform this data into a new Array structured as follows:

heards:[
  {
    text: 'Heading One Of The Table',
    value: 'heading_one_of_the_table'
  },
  {
    text: 'Total',
    value: 'total'
  }
]

I'm attempting to adjust the code to handle more than two headers in case the response contains three object items for each array value. For example:

 "data": [
      {
        "heading_one_of_the_table": 14,
        "heading_two_of_the_table": 8,
         "total": 8
      },
      {
        "heading_one_of_the_table": 1,
        "heading_two_of_the_table": 8,
        "total": 7
      },
      {
        "heading_one_of_the_table": 6,
        "heading_two_of_the_table": 8,
        "total": 7
      }
    ]

resulting in the headers array be updated accordingly:

heards:[
  {
    text: 'Heading One Of The Table',
    value: 'heading_one_of_the_table'
  },
  {
    text: 'Heading Two Of The Table',
    value: 'heading_two_of_the_table'
  },
  {
    text: 'Total',
    value: 'total'
  }
]

I've tried using splice on the "_" symbol and then applying toString().toUpperCase(), however, it did not yield the desired outcome. Any suggestions would be greatly appreciated!

Answer №1

Given that the initial data row consistently includes all header information.

const new_data = [
      {
        "first_heading_of_the_table": 14,
        "second_heading_of_the_table": 8,
         "total": 8
      },
      {
        "first_heading_of_the_table": 1,
        "second_heading_of_the_table": 8,
        "total": 7
      },
      {
        "first_heading_of_the_table": 6,
        "second_heading_of_the_table": 8,
        "total": 7
      }
    ];

const column_headers = Object.keys(new_data[0]).map(val => ({
  text: val.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' '),
  value: val,
}));

console.log(column_headers);

Answer №2

Check out this handy function that can transform the given array.

const information = [
  {
    "category_one": 14,
    "amount": 8
  },
  {
    "category_one": 1,
    "amount": 7
  },
  {
    "category_one": 6,
    "amount": 7
  },
]

const alterArray = arr => {
  const result = []
  for (const info of data) {
    let value = Object.keys(info).find(key => key !== 'total')
    let text = value.split('_')
      .map(word => word.slice(0, 1).toUpperCase() + word.slice(1))
      .join(' ')
    result.push({ value, text })
  }
  return result
}

console.log(alterArray(information))

View the fiddle here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Vue 3 to transform an item within a list by referencing its index

Storing the element's index in a global variable is causing issues when trying to individually edit each of them. Adding multiple elements with similar properties but being unable to edit them separately due to alterations affecting the rest is a chal ...

Tips for passing props while clicking on a v-data-table:

I am currently facing an issue in my app while using v-data-table. I am able to pass props with an extra slot, but I want the entire row to be clickable in order to open a dialog with the prop item: <template v-slot:item.actions="{ item }"> ...

I'm experiencing an issue where a function call within a Vue.js v-for directive causes the loop to continue indefinitely, but I'm unsure of the cause

Here is the template I am working with: <template> <div> <div v-for="report in reports"> <div class="map" v-bind:id="mapID = report.started.toUpperCase()" v-text="report.started"> {{hello(mapID)}} </div& ...

The v-data-table is unable to fetch the user list information from the API using Axios

How can I solve the issue of displaying "No data available" in the user list data table on my userDirectory page? I have created a userDirectory page with a subheader and a data table from Vuetify, but it seems to have no data available. <template> ...

Performing function in Vue.js when a change occurs

I recently started developing a Vue.js component that includes an input field for users to request a specific credit amount. My current goal is to create a function that will log the input amount to the console in real-time as it's being typed. Ultima ...

The absence of text is not displayed in an empty slot of a Buefy table

Currently, I am working on a Nuxt project with Buefy implementation. I attempted to create a table with an #empty slot that displays a message when no data is available. However, my code does not seem to be working as expected. If you refer to the Buefy do ...

JavaScript string: Use regex to find and replace with position index

I'm not very familiar with regex, so I'm curious about the process of replacing a section in a string based on a regex pattern where the index is part of the identified section. Let's consider this example string: let exampleStr = "How do ...

Cypress and VueJS: How to target elements that are dynamically generated following a specific user interaction

I am currently testing a new feature where a button will only appear for the user to click after they have completed another action. Before proceeding with the action, I am verifying if the button exists: cy.get('span') .contains('Selec ...

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...

Unusual "visual" phenomenon with autocomplete feature in VUE.js

Can someone review this code snippet? Check out the code here This is a peculiar example of a custom autocomplete VUE component. If you enter a value in one of the fields in Section 1 (like 'Apple'), then click on the Next button, you'll ...

The pie chart fails to fully display

Check out the repro example I made here. The legend is displaying properly, but the graph is not showing up. What could be causing this unexpected issue? ...

An object will not be returned unless the opening curly bracket is positioned directly next to the return statement

compClasses: function() { /* The functionality is different depending on the placement of curly brackets */ return { major: this.valA, minor: this.valB } /* It works like this, please pay attention to ...

While making a promise, an error occurred: TypeError - Unable to access the property '0' of null

I encountered an issue when trying to assign data from a function. The error appears in the console ((in promise) TypeError: Cannot read property '0'), but the data still shows on my application. Here is the code: <template> ...

Steps to efficiently enumerate the array of parameters in the NextJS router:

In my NextJS application, I have implemented a catch all route that uses the following code: import { useRouter} from 'next/router' This code snippet retrieves all the parameters from the URL path: const { params = [] } = router.query When I co ...

Having trouble getting a JS file to work with the Laravel Inertia.js and Vue.js3 template

Just getting started with inertia.js and facing an issue. My CSS styles are being applied, but my JavaScript file isn't functioning as expected. I'm working on an admin dashboard using Laravel 9 and vue.js-3 with a custom HTML template. Interes ...

Can you explain the meaning behind the code Array.remove = function() {...}?

I encountered this code snippet that has left me puzzled: Array.remove = function(array, from, to) { var rest = array.slice((to || from) + 1 || array.length); array.length = from < 0 ? array.length + from : from; return array.push.apply(arr ...

Is there a way to call a Vue function from an onclick event in JavaScript?

Creating a vue component and trying to call a function defined in Vue methods using the onClick attribute when modifying innerHTML is resulting in an error message stating "showModal is not defined". Here is the showModal function where I'm simply try ...

Experimenting with a customizable Vue.js autocomplete feature

Check out this sample code: https://jsfiddle.net/JLLMNCHR/09qtwbL6/96/ The following is the HTML code: <div id="app"> <button type="button" v-on:click="displayVal()">Button1</button> <autocomplete v- ...

Is there a way to extract only the value from the most recent request?

While working with VueJS, I have a handler for changes in an input field that looks like this: inputHandler(url, params){ const p = new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('POST&ap ...

Component fails to trigger @click handler

.vue component <template> <div class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> Loading Files </div> < ...