Question

I have a codepen representing my question: http://codepen.io/anon/pen/ibwvl

In the codepen, I create some simple plugin init functions and log out the settings when the app begins to run.

My question is, when I console.log(app.settings) I see my default object, along with the new options object merged together, but I do not see the last key inside of me defaults object (foo3). Is this because the default object is overwritten by the options object when $.extend() runs? If so, is there any way to merge nested objects with $.extend()?

For clarity:

default object:

var defaults = {
      test: 'foo',
      obj: {
        key1: null,
        key2: null,
        key3: 'foo3'
      }
    }

options object:

$('#foo').fooTest({
  obj: { 
    key1: 'foo1',
    key2: 'foo2'
  }
});

result when logging app.settings:

test: 'foo',
          obj: {
            key1: null,
            key2: null
          }
        }

Where did key3 go?

Was it overwritten because of the options plugin defining the new obj as obj: {}?

If so, how can I use extend with nested objects and ensure they don't get overwritten?

Was it helpful?

Solution 2

Yes, you object is being overwritten. But fortunately, $.extend accept boolean as first parameter that allow deep extension.

Just do :

app.settings = $.extend(true, defaults, options); //this will override defaults
app.settings = $.extend(true, {}, defaults, options); //this will not
//app.settings will be the same with both way

Deep extension

OTHER TIPS

Use deep parameter of the jQuery.extend function. This will make extend function work recursive.

app.settings = $.extend(true, {}, defaults, options); 

From here, you can find more examples about jQuery.extend function and its usage.

But be careful since it is added in jQuery v1.1.4 and as official documentation said, passing false for the first argument is not supported.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top