简体   繁体   中英

How should I go about using jQuery extend when my config file has a normal array in it?

Seems $.extend uses only the keys of its input to determine what to overwrite. So when my config looks like this

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

and is extended with more keycodes to add to the whitelist, extend simply overwrites the defaults with the new keycodes one by one even though they are different values.

I'm thinking about solving this problem by typing the keys like this 37: 37, 39: 39 etc. I would love a solution that doesn't force me to mess up the syntax of my configuration though.

You might want to use merge instead of extend:

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 merge every single array:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM