I am writing the following function in javascript:
Number.prototype.niceFormat(options) {
var defaultOptions = {
thousandSeparator: ',',
leftPad: 0,
decimalPlaces: 2
};
if (typeof options.thousandSeparator != 'undefined'
&& options.thousandSeparator != null) {
defaultOptions.thousandSeparator = options.thousandSeparator;
}
}
The troublesome thing is I want options to be entirely flexible.
if I call the niceFormat({decimalPlaces: 3})
, then the defaultOptions
property decimalPlaces
is replaced accordingly.
I would hate to write the if statement as many times as there are properties in the defaultOptions
.
Is there a nice way to flexibly overwrite the value of the properties in defaultOptions
?
Basically I am looking for a sort of array_merge
for objects in javascript.
UPDATE:
I took the answers from Qantas and Crayon and Paul comment and wrote this:
Number.prototype.niceFormat = function(options) {
var defaultOptions = {
thousandSeparator: ',',
leftPad: 0,
decimalPlaces: 2
};
var env = defaultOptions;
if (typeof options != 'undefined') {
for (option in env) {
if (options.hasOwnProperty(option)
&& typeof options[option] != 'undefined') {
env[option] = options[option];
}
}
}
Anyway to improve this further?