1

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.

Darren
  • 13,050
  • 4
  • 41
  • 79
  • 2
    Why didn't you test it? – Mik378 Nov 11 '14 at 00:48
  • 2
    The expression in the first example will be executed when you do the `var prices` assignment, not every time you access the element. – Barmar Nov 11 '14 at 00:48
  • 1
    There's no point in calling `parseFloat()` on the result of a multiplication. You should call `parseFloat` on the strings that are in the properties _before_ multiplying them. – Barmar Nov 11 '14 at 00:49
  • 2
    Keep in mind that using a getter will not work in IE8 – james emanon Nov 11 '14 at 00:52
  • Have tested it, it seems the answers solve the issue I was facing. Also thanks @Barmar for that note! – Darren Nov 11 '14 at 00:52
  • possible duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – Qantas 94 Heavy Nov 11 '14 at 01:07

2 Answers2

2

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
Sampath Liyanage
  • 4,776
  • 2
  • 28
  • 40
1

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.

jAndy
  • 231,737
  • 57
  • 305
  • 359