Question

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?

Was it helpful?

Solution

What you need to do is check both contain that property, then assign to it:

for (var i in options) if (options.hasOwnProperty(i) && defaultOptions.hasOwnProperty(i)) defaultOptions[i] = options[i];

hasOwnProperty() checks that the property is directly on that object (not through any prototype or something) and that it actually exists on the object.

OTHER TIPS

for (option in defaultOptions) {
  if (typeof options[option]=='undefined') options[option] = defaultOptions[option];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top