Executing mathematical calculations within a JavaScript object

Can an equation be executed inside an object? For instance:

var taxes = {
    gst: '0.10',
};

var prices = {
    first_key: '437.95',
    total_key: parseFloat(prices.first_key * taxes.gst).toFixed(2),
    .......
    },
};

Or do I need to utilize a function?

var prices = {
    total_key: function() { return parseFloat(prices.first_key * taxes.gst).toFixed(2);}
}

If possible, can it be done as shown in the first example?

Cheers.

Answer №1

Implement javascript object getters for accurate calculations.

var prices = {
    item_one: '437.95',
    get total_amount(){return parseFloat(this.item_one * taxes.gst).toFixed(2)},
    .......
    },
};

To retrieve the total amount, use:

prices.total_amount

Answer №2

To simplify your code, you can create a special function, known as a getter function, that functions like a property. Here's an example:

var details = {
    item_code: 'A123',
    get total_price() {
        return (parseFloat( this.item_code ) * parseFloat( taxes.vat ) ).toFixed( 2 );
    }
};

Now, you can easily retrieve the total price by using:

details.total_price;

This will give you the calculated result.

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

Is there a way to ensure that a statement will not execute until the completion of a preceding function?

I am encountering an issue where the window.open function is being called too quickly, causing my other function not to finish and post in time within my onclick event. I attempted to address this by setting a timeout on the trackData() function, but it o ...

Obtain the JSON response from the servlet

Is there a way to get a JSON response from a servlet in JavaScript? I am using AJAX post to send data to the servlet. Here is my AJAX code $.ajax({ type: "POST", url: "formDelegationServlet", data: { ...

Shuffling arrays with JavaScript and jQuery for a touch of randomness

Looking to add some variability to your font choices? I've got an idea for you! How about randomizing three arrays for fonts, font size, and font weight? Then, we can display the results of these arrays in a div with the class name "randomFont." Each ...

Transforming the text to a new line

I have been attempting to format lengthy texts from a JSON file, but I haven't been successful. The text keeps displaying as multiple sections within a single response, which can be seen in the image below. I've tested solutions like word-break a ...

Can you explain the syntax for the Javascript tag?

While browsing through some code, I stumbled upon this snippet and found myself puzzled by the not:. Is it a tag of some sort? And if so, are there alternative applications for it? var foo = { not: function(bool) { return !bool; } } I'm curious t ...

Error message: "Reactjs - TypeError: The property 'map' cannot be read as it is undefined in the table"

I have encountered an issue while using the material-ui table. I am able to map the items and display them successfully, but when trying to map the orders.items in the table, I get the following error: TypeError: Cannot read property 'map' of u ...

jQuery page hanging during DOM update with large data set

I am currently using a jQuery post method with the following structure: $.post("/SearchCompetitor/Index", { username: _username }, StartLoading()) .done(function (data) { if (data !== "UsernameErro ...

Transforming an SQL Query into JSON format using Oracle 11g in Oracle Application Express (APEX)

In my Oracle APEX v4.2 project, I am dealing with a sizable table containing about 40 columns and up to 50 rows. My goal is to use SQL to fetch the data from this table and convert each row into a JSON object. Operating on Oracle 11gR2, I require this JSO ...

Using AngularJS to auto-fill input and textarea fields

In order to test local storage, I created a ToDo list using angularJS. Within my mainController, the following code snippet is present: $scope.saved = localStorage.getItem('todos'); $scope.todos = (localStorage.getItem('todos') !== n ...

Modify Javascript to exclusively focus on SVG paths

I successfully created an SVG animation using JSFiddle, but when I transferred the SVG to Shopify, the Javascript that animates the path stopped working. It seems like the issue is with the JavaScript targeting all paths on the page instead of just the sp ...

Creating a list using variables through a Post Request in Express

I am currently exploring how to create a list using a Post Request in Express. I am fetching Video Game data from an API and aiming to use this data to populate specific details within a list. For illustration: let name = localStorage.getItem("name"); let ...

Having trouble getting a value from a textbox to PHP using jQuery - can anyone lend a hand?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.5b1.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js"></script> <input type="text" id= ...

Asynchronous setTimeout for server-side operations

I am currently facing an issue with my web server. Whenever a request is made, the server initiates a phone call, waits for 3 seconds, and then checks if the call is still ongoing. I have utilized setTimeout to achieve this functionality, but it seems to b ...

Fixing Timezone Issue in VueJs 3 with Axios POST Request

Having an issue with axios. In my application, I have an input field for datetime-local. When I select a date and time, the displayed time is correct (e.g., selecting 10:00 shows as 10:00), but when calling a function using axios.post, the request sends th ...

After changing the form action using jQuery, the GET variables mysteriously vanish

I am attempting to modify the action URL of a form using jQuery. Below is the code I have implemented: <form id='form_a' action='browse.php' method='get'> <input type="submit" value="Filter" id='but_a'& ...

Making an Ajax request with JSON is yielding unexpected variables that cannot be modified or removed

Attempting to make an AJAX call using a script: $.ajax({ url: pageURL, data: loadData, type: 'POST', cache: false, dataType: 'json', success: function (data) { //if the call was successful console.log(su ...

Leveraging the Request npm package synchronously within Meteor 1.3

In my Meteor 1.3.2.4 project, I tried utilizing the synchronous features of the request npm package. I initially followed the instructions provided in this guide article from Meteor and attempted to use Meteor.bindEnvironment. Here's the code: impor ...

I am experiencing an issue where Discord.js is unable to assign a role to a new member upon joining my server

I'm trying to set up my bot to automatically assign a specific role to new members when they join the server. However, I keep encountering a strange error that I can't seem to figure out. Here is the code snippet in question: const { GuildMember ...

The function cannot be called because the type does not have the appropriate signature for invoking. The specific type lacks compatible call signatures, as indicated

Encountering an issue while attempting to utilize a getter and setter in my service, resulting in the following error message: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures 2349 t ...

JavaScript function for automatic scrolling to the bottom of the page is not functioning as expected

I'm working on incorporating a terminal/console feature into my website. I came across the JavaScript functions for scrolling down a page, namely window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeSc ...