Darren
Darren

Reputation: 13128

Running equation in javascript object

Is it at all possible to run an equation inside an object? An example of what I'd like to achieve is:

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

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

Or am I going to have to run it through as a function?

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

If at all, is it possible to do it as the first option?

Cheers.

Upvotes: 1

Views: 85

Answers (2)

jAndy
jAndy

Reputation: 236092

You can setup a getter function, which pretty much is a function, but behaves as a property. That could look like

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

Now you can just access

prices.total_key;

and you get the result.

Upvotes: 1

Sampath Liyanage
Sampath Liyanage

Reputation: 4896

Use javascript object getters.

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

then to access value,

prices.total_key

Upvotes: 2

Related Questions