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

Having trouble deleting multiple rows with ng-repeat in datatables

Having followed the instructions in this post, I quickly integrated it with jquery datatables. However, the functionality is not as expected. When attempting to delete rows, they do not get deleted. Furthermore, if I navigate to the next page and return, ...

How can you rearrange the order of objects in an array to only include duplicates?

I don't want to alter the original order of objects in an array. However, I do need to retrieve items in a specific sequence when both the location and place are identical. I attempted a solution but it requires an additional condition. var ...

Issue with Caching during Javascript Minification

I Have ASP.Net MVC 3 App. Utilizing YUICompressor.Net for compressing Javascript and CSS files post build with MSBuild. The minimized javascript file is named JSMin.js and the CSS file is CssMin.css. In my master page, I reference these files as shown bel ...

How can you create an event that is focused on options using Material-UI's Autocomplete feature?

This is regarding Material-UI's Autocomplete feature. I am looking for a way to track which autocomplete choice the user is currently focused on, whether it be through hovering over with the mouse or using keyboard arrows - before any actual selection ...

Is there a way to modify the button's color upon clicking in a React application?

I am a beginner in the world of React and currently exploring how to utilize the useState hook to dynamically change the color of a button upon clicking. Can someone kindly guide me through the process? Below is my current code snippet: import { Button } ...

Modifying Arrays with Different Data Structures in JavaScript

I am interested in implementing the following scenario: var A = ["Jon","Brad","Rachel"]; var B = ["Male","Male","Female"]; var C = [ {"Jon","Male"}, {"Brad","Male"}, {"Rachel","Female"} ] Can you guide me on how to retrieve var C using javascrip ...

What is the best way to showcase arrays in a JSON document?

I'm working on a basic AJAX code to show a JSON file stored locally using this HTML, but I keep getting an 'undefined' error. I'm opting for JavaScript instead of JQuery since I haven't delved into it yet; hoping my code is syntact ...

Having trouble getting the Next.js Image component to work with Tailwind CSS

Recently, I've been working on transitioning a React project to Next.js and encountered some issues with the next/Image component that seem to be causing some problems. <div className=" flex flex-col items-center p-5 sm:justify-center sm:pt-9 ...

When using AngularJS and PHP together, I encountered an error that stated "

My POST http request is encountering an error with the message Undefined property: stdClass::$number and Undefined property: stdClass::$message. Below are the codes I've been using: smsController.js angular .module('smsApp') .contr ...

javascript issue with showing content on click

I'm currently working on a school assignment where I am using the onclick() function to display information about an object. However, I am facing an issue where the information is not popping up as expected. HTML <!DOCTYPE html> <html> ...

How do I navigate to the homepage in React?

I am facing an issue with my routes. When I try to access a specific URL like http://localhost:3000/examp1, I want to redirect back to the HomePage. However, whenever I type in something like http://localhost:3000/***, I reach the page but nothing is dis ...

"Utilizing the jQuery append method to dynamically insert an SVG element

Currently, I'm in the process of constructing a graph by utilizing svg elements and then dynamically creating rect elements for each bar in the graph through a loop. I have a query regarding how I can effectively pass the value of the "moveBar" varia ...

the language of regular expressions expressed in strings

As a beginner in Javascript and regular expressions, I found myself stuck on how to create a route that matches all URLs starting with /user/.... Initially, I thought of using app.get(/user/, function(req, res){ /*stuff*/}); However, curiosity led me to ...

Sorting by price using the ng-repeat directive is not suitable for this

Utilizing angular's ng-repeat along with orderBy on a product catalog page to sort the products based on a select change. The ordering by name using orderBy works as expected, however, when it comes to price it sorts like this: 1,10,11,12,13,14,2,3,4 ...

What is the best way to connect a relative CSS stylesheet to a master page?

My Java application generates several HTML pages, organized in different directories: html_pages/ | ----> landin_page.html html_pages/details | ----> index1.html html_pages/more_details | ----> index2.html html_pages/css | ...

Launch the Image-Infused Modal

I am completely new to the world of Ionic development. Currently, I am working on a simple Ionic application that comprises a list of users with their respective usernames and images stored in an array. Typescript: users = [ { "name": "First ...

Guide to dividing a URL in reactjs/nextjs

Here is the complete URL: /search-results?query=home+floor&categories=All+Categories. I am looking to separate it into two sections - /search-results and query=home+floor&categories=All+Categories. My objective is to extract the second part of t ...

Is there a way to manage the state of a dictionary nested within a list using React JS?

Below is a snippet of my code. I am attempting to update the state of data (which is contained within datasets) to a value defined by the user. constructor(props) { super(props); this.state={ value:'', set:[], coun ...

Utilizing Regular Expressions to Substitute 'null' in API Data with a Custom String in JavaScript

I'm working with an API to gather information about books, including the title and author. However, I've noticed that some authors' data is returned as 'undefined'. I had the idea of using regular expressions (RegExp) to replace th ...

Utilizing HTML and JavaScript to Download Images from a Web Browser

I'm interested in adding a feature that allows users to save an image (svg) from a webpage onto their local machine, but I'm not sure how to go about doing this. I know it can be done with canvas, but I'm unsure about regular images. Here i ...