How should I use the jQuery extension when there is a normal array in my configuration file?

It seems that $.extend uses only its input keys to determine what to overwrite. Therefore, when my config looks like this

 var config = { "numeric" : false, "keycode_whitelist" : [ 37, 39, // Left, right 9, // Tab 17, // Ctrl 116 // F5 ] }; 

and expands with additional code keys to add to the white list, simply overwriting the default new key codes one at a time, even if they are different values.

I’m thinking about solving this problem by typing keys like this 37: 37, 39: 39 , etc. I would have liked a solution that did not make me mess up the syntax of my configuration.

+4
source share
1 answer

You can use merge instead of extension:

 var config = { "numeric": false, "keycode_whitelist": [ 37, 39, // Left, right 9, // Tab 17, // Ctrl 116 // F5 ] }; var custom = { "somevalue": "some other things", "keycode_whitelist": [ 1, 2, 3 ] }; var newopts = $.extend({}, config, custom); newopts.keycode_whitelist = $.merge(custom.keycode_whitelist, config.keycode_whitelist); 

Demo: http://jsfiddle.net/3Q4cF/2/

Update:

To combine each individual array:

 $.each(config, function(key, obj){ if($.isArray(obj)) { if(custom[key]) { newopts[key] = $.merge(config[key], custom[key]); } } } ); 

http://jsfiddle.net/3Q4cF/5/

+4
source

All Articles