How to merge user option with default options using jQUery's extend()
method when the options object has a property that has a value that is an array of objects
example:
var settings4 = $.extend({
type: 'one-panel', // 'one-panel' | 'two-panel'
sidebarTargets: [
{
targetKey: 'sidebar-one',
initialLoadPanelKey: 'panel1',
emptyPanelMessage: '',
sidebarWrapSelectorId: 'sidebar-container',
sidebarPanelWrapTemplate: '<div class="sidebar-panel {panelInitialSlideCss}" id="{panelSelectorId}" data-panel-key="{panelKey}"></div>',
showHeader: true,
headerTemplate: '<div class="sidebar-header" id="sidebar-header">Header text</div>',
},
// if sidebarSettings.type == one-panel, this is not required
{
targetKey: 'sidebar-two',
initialLoadPanelKey: 'none',
emptyPanelMessage: '<span>No Notebooks Notes Found',
sidebarWrapSelectorId: 'sidebar-container',
sidebarPanelWrapTemplate: '<div class="sidebar-panel" id="{panelSelectorId}" data-panel-key="{panelKey}"></div>',
showHeader: true,
headerTemplate: '<div class="sidebar-header" id="sidebar-header">Header text</div>',
},
{
targetKey: 'right-content-panel',
selectorId: 'sidebar-container',
cssClassLIst: 'content-panel content',
showLoader: true, // when AJAX content is loaded, show a loader spinner
loaderTemplate: '',
initialInnerContent: '',
},
{
targetKey: 'right-content-iframe-panel',
selectorId: 'sidebar-container',
cssClassLIst: 'content-panel content',
iframeNameAttribute: 'content',
template: '<iframe id="content-frame" src="default.html" name="content" width="100%" height="100%" frameborder="0"></iframe>',
}
],
}, sidebarOptions);
The object property above sidebarTargets
is the one in question. It can contain any number of objects in the array. How do I use jQuery's extend to merge options and handle a property like this?
I'm afraid you can't really do this using jQuery's extend
function .
The extend
will be able to extend objects you have, if you send true
in your first argument . The problem is that you have Array
s in your object, and the extend
will not know what to do with those Arrays.
If you are able to change the code to objects, this will work great:
var a = { a: ['a'], b: { 'c': 1 } } var b = { a: ['b'], b: { 'd': 2 } } $.extend(a, b) console.log('regular extend:') console.log(a); console.log('') var a = { a: ['a'], b: { 'c': 1 } } var b = { a: ['b'], b: { 'd': 2 } } $.extend(true, a, b) console.log('deep copy extend:') console.log(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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.