Guide to rounding values retrieved from JSON object using Math.round in Vue.js

I'm currently working on a Vue 3 component using the Composition API that fetches values from a JSON object and displays them on the screen. The component reads data from a local data.json file and returns these values to the template. The JSON file consists of a single object with multiple values, and my goal is to round each value to the nearest whole number using Math.round(). To achieve this, I've created a computed property that rounds the values as follows:

        const data = ref({})
        const roundedData = computed(() => roundedValue())

        const getData = async() => {
            try {
                const res = await axios.get('data.json')
                data.value = res.data
                console.log(data.value)
            } catch(error) {
                console.log(error)
            }
        }

        onMounted(() => {
            getData()
        })

        const roundedValue = () => {
            return Math.round(data.value)
        }

However, the current setup doesn't round the individual values (val, val2, val3, val4) within the object. How can I use Math.round() or Math.toFix(2) to collectively round all the returned values from data.json?

Here's the remaining code:

Component (with Tailwindcss):

<template>
  <div>
    <div class="px-4 py-6 sm:px-0">
        <div class="bg-white shadow overflow-hidden sm:rounded-lg">
            <div class="border-t border-gray-200">
                <dl>
                <div class="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                    <dt class="text-sm font-medium text-gray-500">Value One</dt>
                    <dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{{ roundedData.val }}</dd>
                </div>
                <div class="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                    <dt class="text-sm font-medium text-gray-500">Value Two</dt>
                    <dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{{ roundedData.val2 }}</dd>
                </div>
                <div class="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                    <dt class="text-sm font-medium text-gray-500">Value Three</dt>
                    <dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{{ roundedData.val3 }}</dd>
                </div>
                <div class="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                    <dt class="text-sm font-medium text-gray-500">Value Four</dt>
                    <dd class="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">{{ roundedData.val4 }}</dd>
                </div>
                </dl>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
import { onMounted, ref, computed } from 'vue'
import axios from 'axios'
export default {

    setup() {
        const data = ref({})
        const roundedData = computed(() => roundedValue())

        const getData = async() => {
            try {
                const res = await axios.get('data.json')
                data.value = res.data
                console.log(data.value)
            } catch(error) {
                console.log(error)
            }
        }

        onMounted(() => {
            getData()
        })

        const roundedValue = () => {
            return Math.round(data.value)
        }

        return {
            data,
            roundedData
        }
    }
}
</script>

Data.json:

{
    "val": 1.446565,
    "val2": 45.678,
    "val3": 56.75,
    "val4": 78.98
}

Answer №1

> function calculateRoundedValues() {
>    const roundedData = {}

>    Object.keys(inputValues).forEach(key => {
>     return roundedData[key] = Math.round(inputValues[key]);                
>    })
> 
>   return roundedData
> }

You can give this a shot. The function will provide the rounded values for the input.

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

The error message "Trying to use an undefined constant success - assumed 'success'" appeared while parsing the JSON response

After implementing Google reCAPTCHA with validation through AJAX, everything seems to be functioning correctly as I received a response: { success: "false/true" } However, an error occurred stating "Use of undefined constant success - assumed 'succe ...

How can we universally detect and resolve the user's language within a React/Next.js application using an Apollo client HOC?

Currently, I am developing an I18n module utilizing the Next.js framework (v5). The challenge I am facing is determining the user's default language universally in order to display the UI in that language. While it is relatively simple to resolve th ...

Retrieving JSON data from a URL using Java and HTTPS

Having trouble fetching the JSON from this URL: . Although it's accessible through a browser, I'm unable to succeed. Could someone please share a code snippet to help me out? ...

The iPad scroll did not meet the condition for reaching the bottom

Looking to modify the footer when the bottom of the page is reached via scrolling, I implemented the following code: if($(window).scrollTop() + $(window).height() == $(document).height()) This condition successfully detects whether the scroll has reached ...

Activate the Navbar by clicking on the bar and change the color of the icon

Is it possible to change the background color and icon color when clicking on the bar (active bar)? If not, is there an option to switch the icon with a different color? I've tried modifying my code but haven't seen any changes. Instead of using ...

performing nested queries in nodejs using a callback function

Over the course of my research, I've come across numerous examples of one-to-many relations. However, I have yet to find a clear-cut example demonstrating how to solve nested queries for normalized data in 'mongodb'. Perhaps it's just m ...

Utilize a custom Codable-compliant model to extract and interpret a designated section of a JSON reply

Imagine having an API with a sample response structured like this: https://i.sstatic.net/vLfaC.png A model is created as follows: struct Post: Codable { var id: Int var title: String var body: String var userId: Int } However, decoding u ...

Special characters cause Ajax post to malfunction

My goal is to pass the content of a textarea to a PHP page for processing and storing in a SQL database. I need the textarea to handle special characters without any issues. However, when I input the following string into the textarea and submit it: J ...

Having trouble with a Vue3 project after running a Vite build in production mode?

When I run my project in development mode, everything works perfectly fine. However, when I build the project using `vite build´, some components stop functioning. Oddly enough, there are no errors displayed in the console or in the build logs. If I use ...

Converting JSON Schema into a JSON template using Python

After scouring countless web pages and guides, I have yet to find a solution that suits my needs. Before attempting to create my own, I thought I would ask for advice... Is there a package or simple way to convert a JSON schema in Python to a basic JSON t ...

Updating the value of an element within a JSON array using Python

After retrieving the following collection from an http request: [{'ParameterKey': 'AdminCCIDRBlock', 'ParameterValue': '10.10.196.0/23'}, {'ParameterKey': 'MyParameter', 'ParameterValue&ap ...

Utilize ObjectMapper to parse JSON data into an Object that holds a String and a List of Strings

My scenario involves an Object structured like this: public class Marketplace { private String name; private int id; private List<String> supportedLanguages; } Additionally, I have a Json format input String that loo ...

PHP parsing JSON

Need assistance with decoding JSON and inserting values into MySQL. Take a look at my code below: $json = ' {"d":[{"Id":1059,"Name":"Alfa Romeo - 145"},{"Id":20020,"Name":"Alfa Romeo - 146"},{"Id":1060,"Name":"Alfa Romeo - 147"},{"Id":20021,"Name":"A ...

Issue with Bootstrap List Group Nested Links causing them to stop functioning after initial selection

I am trying to implement page navigation using the Bootstrap List-group class in HTML. However, I am facing an issue where the nested links 'Link 1' and 'Link 2' freeze after the first click. The desired functionality is as follows: ...

There is no such property - Axios and TypeScript

I am attempting to retrieve data from a Google spreadsheet using axios in Vue3 & TypeScript for the first time. This is my initial experience with Vue3, as opposed to Vue2. Upon running the code, I encountered this error: Property 'items' does ...

Why would triggering an input event have any effect if it doesn't appear to be utilized anywhere?

We have developed a custom Vuetify 3 component known as FilterPanel. Here is a simplified version: <template> <div> <v-container> <v-row> <v-col cols="3"> <v-select v-model="fiel ...

Executing JavaScript code within an AJAX request

Having a problem with an AJAX function that I need help solving: PAGE A represents the main page. PAGE X represents the content loaded via AJAX. RES A represents the results from PAGE A. RES B represents the new results loaded via AJAX. PAGE A initially ...

Steps for creating a new column specifically for storing JSON values in a database table

I have come across this script: #!/bin/bash # rsync using variables echo 'Id,Name,Amount,TS,unique_ID' > lfs.csv epoch=$(date +%s) u_id=0 for (( id=1 ; ;id++ )) do [[ $u_id == 100 ]] && (( u_id = 1 )) || (( u_id +=1 )) echo $ ...

Can you provide guidance on implementing StyledComponents within the app folder of Next.js version 13?

Quoting information from the Next.js documentation: Attention: CSS-in-JS libraries that rely on runtime JavaScript are currently not compatible with Server Components. The following libraries are supported in Client Components within the app directory: s ...

Executing API POST requests by iterating over an array in ECMAScript 6

My dilemma lies in processing an input that follows the format of "ABC, DEF, GHI, ...." The task at hand is to convert this comma-separated list into an array and make a POST request for each value in the array using my API. I'm seeking guidance on t ...