JQuery extension overwrites invalid values

I use jQuery extend in the plugin to overwrite the default options. However, I have a problem.

Here is my array of default settings:

 slider.settings = { background: { animation : { direction : 'horizontal', increment : 15 //can be any number } } } 

Now I want to overwrite the direction parameter. Here is the array I will merge with using extend :

  settingsToOverwrite = { background:{ animation:{ direction:'vertical' } } } 

Now I will combine the two:

 slider.settings = $.extend(slider.settings, options) 

I see that the direction value has been updated. However, there is no more growth. I know that in order to avoid this problem, I could only set the parameters at the first level, but I see more clarity of the code, fulfilling my path. Is there any way to do this? If not, I will change everything to be only one level.

+6
source share
2 answers

By default, jQuery.extend() compares only the immediate properties, performing a "shallow merge". Since both objects have background , it just takes all background from the second object.

But pass a true as the first argument, and jQuery.extend() will do a deep merge.

 slider.settings = $.extend(true, slider.settings, options); 

Also, since 1st Object is target and will be changed and return 'd, you can only update slider.settings with

 $.extend(true, slider.settings, options); 

And, if you prefer to have a new Object from a merge, you will have to create it yourself:

 slider.settings = $.extend(true, {}, slider.settings, options); 
+11
source

You're right, this obviously happens because the jQuery extension is a "small extension" of the object .. thus replacing the entire animation property.

To fix this, use your dandy deepExtend brandy:

 Object.deepExtend = function(destination, source) { for (var property in source) { // loop through the objects properties if (typeof source[property] === "object") { // if this is an object destination[property] = destination[property] || {}; Object.deepExtend(destination[property], source[property]); // recursively deep extend } else { destination[property] = source[property]; // otherwise just copy } } return destination; }; 

You can use it as follows:

 slider.settings = Object.deepExtend(slider.settings, options); 
+2
source

Source: https://habr.com/ru/post/950484/


All Articles