0

Say I have a Form object which has an array of Tab objects.

var Tab = function (options) {
    return ($jQuery.extend(true, {
        id: 'foo',
        title: 'Foo'
    }, options));
}

var Form = function (options) {
    return ($jQuery.extend(true, {
        id: 'foo',
        tabs: [new Tab()]
    }, options));
}

I can use this:

var myForm = new Form({tabs: [new Tab({id: 'bar'}), new Tab({title: 'Bar'}), new Tab({id: 'bar', title: 'Bar'})]});

To get:

myForm.tabs[0] => {id: 'bar', title: 'foo'}
myForm.tabs[1] => {id: 'foo', title: 'Bar'}
myForm.tabs[2] => {id: 'bar', title: 'Bar'}

But is it possible to somehow do this:

var myForm = new Form({tabs: [{id: 'bar'}, {title: 'Bar'}, {id: 'bar', title: 'Bar'}]});

And get the same result?

1 Answer 1

0

You can loop over the tabs and check whether they are a Tab object, e.g. (untested):

var Form = function (options) {
    if(options && options.tabs) {
        var tabs = options.tabs;
        for(var i = 0, l = tabs.length; i < l; ++i) {
            if(!(tabs[i] instanceof Tab)) {
                tabs[i] = new Tab(tabs[i]);
            }
        }
    }

    return ($jQuery.extend(true, {
        id: 'foo',
        tabs: [new Tab()]
    }, options));
}

Reference: instanceof

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I was hoping there would be a simple way of doing this without writing additional code to handle it. This will do the job. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.