Implement a formatter function to manipulate the JSON data retrieved from a REST API within the BootstrapVue framework

My bootstrap-vue vue.js v2.6 app is receiving JSON data from a REST API. The data structure looks like this:

{
    "fields": [
        {
            "key": "name",
            "label": "name",
            "sortable": true
        },  
        {
            "key": "item1",
            "label": "item1",
            "sortable": true
        },
        {
            "key": "item2",
            "label": "item2",
            "sortable": true            
        },
        {
            "key": "item3",
            "label": "item3",
            "sortable": true
        }
    ],
    "items": [
        {
            "name": "Field name 1",
            "item1": -0.05,
            "item2": -0.06,
            "item3": -0.07
        },
        {
            "name": " Field name 2 "
            "item1": -0.01,
            "item2": -0.02,
            "item3": -0.03
        },
        {
            "name": "Field name 3",
            "item1": -0.05,
            "item2": -0.06,
            "item3": -0.07
        }
    ]
}

I want to add a formatter function to display the items in percentage format, specifically for item2.

{
    "fields": [
        {
            "key": "name",
            "label": "name",
            "sortable": true
        },  
        {
            "key": "item1",
            "label": "item1",
            "sortable": true
        },
        {
            "key": "item2",
            "label": "item2",
            "sortable": true,
            "formatter": "value => { return (value + '%')}"
        },
        {
            "key": "item3",
            "label": "item3",
            "sortable": true
        }
    ],
    "items": [
         // Data remains the same
    ]
}

The Vue.js code I wrote for this purpose does not seem to work as expected. It's supposed to display item2 with a percentage sign added at the end but it doesn't. Any insight on what might be wrong would be appreciated.

I am using vue.js v2.6 and BootstrapVue.

Answer №1

Ensure that the formatter field is the actual name of a function when provided as a string, not the string value of the function itself.

If you encounter this issue, simply remove the quotes from the formatter value like so:

// "formatter": "value => { return (value + '%')}" ❌ don't use a string
"formatter": value => { return (value + '%')} ✅

Check out the demo here

Answer №2

To achieve adding a percentage sign as a suffix to the item2 column in a BootstrapVue table, there is an alternative method available.

Define the fields within your JavaScript code and only read data from the REST API json for the items.

It is uncommon for an API to dictate how the table fields should be structured. This information should be incorporated into your own code rather than relying on the API to define it. Extracting this information directly from the API goes against proper architectural design.

Below is an example of how the updated code will appear:

<template>
  <div class="container">
    <h1 class="pt-2 pb-3">Bootstrap Table</h1>
    <b-table striped hover :items="items" :fields="fields" primary-key></b-table>
  </div>
</template>

<script>

async function axiosGetRequest(url) {
  const axios = require("axios");  
  let res = await axios.get(url);

  return res.data;
}

export default {  
  data: data_init,
  mounted: function() {
      let url = "http://localhost:8080/temp.json";   
      
      axiosGetRequest(url).then((res) => {
        //this.fields = amend_fields(res.fields); //Don't read fields data from REST API. Define yourself.
        this.items = res.items;
        console.log(this.fields);
      });        
  },
};

function data_init() {  
  
  let init_data = {};
  init_data.fields = [
        {
            "key": "name",
            "label": "name",
            "sortable": true
        },  
        {
            "key": "item1",
            "label": "item1",
            "sortable": true
        },
        {
            "key": "item2",
            "label": "item2",
            "sortable": true,
            "formatter": "value => { return (value + '%')}"
        },
        {
            "key": "item3",
            "label": "item3",
            "sortable": true
        }
    ];
  init_data.items = {};

  return init_data;
}

</script>

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

Get connected to your favorite music on iTunes without the hassle of opening a new window by simply clicking on the

Is there a way to call a link to iTunes (itms://...) without opening a new window? I've tried using window.open but that just opens a new window. Also, $.get('itms://...'); doesn't seem to work for me. Are there any other options avail ...

Show button once modal has been closed

I have a 'start' button that triggers a modal window with an embedded video. Once the user closes the modal, I want to show a 'redeem' button after a delay of 6 seconds. HTML: <a id="video-start" onclick="openVideoModal()"><i ...

Tips for filling in the values for the options in a select dropdown menu

Currently, I am facing a strange bug related to the select element. Whenever I open the dropdown, there is always a mysterious black option at the top. This is how my HTML looks like: This particular element is part of my test controller. <select ng- ...

Using a variable name to retrieve the output in JavaScript

I created a unique JavaScript function. Here is the scenario: Please note that the code provided below is specific to my situation and is currently not functioning correctly. analyzeData('bill', 'userAge'); Function analyzeData(u, vari ...

Generate a fresh array using the data from the existing array object

I have nested objects within arrays that I need to manipulate. { "page": [ { "num": "1", "comp": [ { "foo": "bar", "bar": "foo", ...

JavaScript and modifying the attributes of the nth child

I'm working on a navigation bar that changes the "background-image" of menu items using the nth-of-type CSS selector. Now, I need to figure out how to dynamically change the picture of the "background-image" when hovering over a specific menu item usi ...

Updating corresponding key values in two JavaScript objectsORModify matched key values

I am in need to compare two objects and update the values of the first object with the updated values from the second object. For example: $scope.obj1={"id" : 1, "name" : "java"} $scope.obj2={"id" : 1, "name" : "java4you", "gender" : "male"} compare(des ...

Troubleshooting issues with AngularJS routing

Having trouble clicking on the show button and seeing anything displayed. I've spent a lot of time on this without success, can someone please assist. Files.... app.js controller.js index.html show.html index.html <html ng-app='Java4sApp& ...

How can I loop the keyframe animation across various elements of an SVG file simultaneously?

After creating an animation using CSS and SVG, I am experiencing different parts of it animating in and out. My goal is to have the animation start from the top once it's finished. There are multiple keyframes involved since I'm animating variou ...

Achieve identical outcomes with PHP's `strlen` function and jQuery's `val().length` method

Currently, I am utilizing jQuery to dynamically count the value of a textarea: function count_chars () { count_chars=$('#text_textarea').val().length; } Upon submission, I serialize the form and send the textarea text via AJAX to a PHP file ...

Next.js throwing an error: TypeError - attempting to read property 'map' of undefined

I am facing an issue with my Next Js project. I have implemented the backend logic to display data, but when I attempt to show all the data using the useEffect hook and the map function, I encounter the following error: TypeError: Cannot read property &apo ...

Separating the logic of identical schemas and implementing multi-tenancy in Node.js using Mongoose

In the system I am developing, there are two key requirements: Each client needs to be completely isolated from one another Clients can have multiple subsidiaries which they should be able to switch between without needing to re-authenticate, while ensuri ...

Extracting information from AJAX calls using a DataTable

When it comes to creating CRUD tables in school, I've always used scaffolding per page. However, I recently wanted to experiment with performing all operations without using Partial View. I decided to implement AJAX by following a tutorial on Everyth ...

What is the method for specifying a specific sub-dependency version in a package in Node.js?

Let me simplify my issue for you. I am facing troubles while trying to install two plugins, plugin A version 2.0 and plugin B version 3.0. It turns out that plugin B has plugin A as a sub-dependency with a conflicting version, resulting in a build phase e ...

Synchronize chat messages automatically with the scrolling window using AJAX technology

Original Content Scrolling Overflowed DIVs with JavaScript In my AJAX chat application, messages are displayed in a div with overflow: auto, enabling the scroll bar when the content exceeds the space. I am looking for a solution that automatically scrol ...

What is the best way to modify a CSS property using logical operators in JQuery?

If an element with the class ".has_padding" does not have any text content, it should be set to "display:none;". However, those elements with text inside should remain visible. Below is some code where I have styled the elements to demonstrate the issue. ...

Rails Navigation Issue: JQuery Confirmation Not Functioning Properly

Having a Rails app, I wanted to replicate the onunload effect to prompt before leaving changes. During my search, I came across Are You Sure?. After implementing it on a form, I noticed that it only works on page refreshes and not on links that take you a ...

Leveraging Selenium for extracting data from a webpage containing JavaScript

I am trying to extract data from a Google Scholar page that has a 'show more' button. After researching, I found out that this page is not in HTML format but rather in JavaScript. There are different methods to scrape such pages and I attempted t ...

Trigger the click event on the ul element instead of the li element using jQuery

Is there a way to make the click event only affect ul tags and not all li elements using jQuery? <!-- HTML --> <ul class="wrap"> <li>test1</li> <li>test2</li> <li>test3</li> </ul> I attemp ...

What is the accurate way to retrieve the icon path for 'manifest.json'?

Within my manifest.json file, I have the following code: "icons": [ { "src": "/static/img/icons/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/static/img/icons/android-chrome-512x512.png", "sizes": "512x512", ...