Caio Kawasaki
Caio Kawasaki

Reputation: 2950

How to $.extend objects with sub-objects in jquery?

I know i can use $.extend({}, x); to merge the contents of two or more objects together into the first object, but my answer is, and the sub-objects? They will only be overwritten? I can't merge then?

I have this:

var settings = $.extend({
    modal: {
        title: "Atention",
        type: "text",
        width: "small"
    },
    ajax: {
        type: "normal",
        trigger: "",
        url: ""
    }
}, {
    modal: {
        title: "Registrar",
        type: "register"
    },
    ajax: {
        trigger: ".bumbum",
        url: "modal/lets/go"
    }
});

This jQuery function will return this:

var setting = {
    modal: {
        title: "Registrar",
        type: "register"
    },
    ajax: {
        trigger: ".bumbum",
        url: "modal/lets/go"
    }
};

And unfortunately I need it:

var setting = {
    ajax: {
        type: "normal",
        trigger: ".bumbum",
        url: "modal/lets/go"
    },
    modal: {
        title: "Registrar",
        type: "register",
        width: "small"
    }
};

Any idea? Thank you.

Upvotes: 3

Views: 460

Answers (1)

thecodeparadox
thecodeparadox

Reputation: 87073

For deep nesting try, $.extend(true, {}, x);. For deep nesting the format is:

jQuery.extend( [ deep ], target, object1 [, objectN ] );

Upvotes: 6

Related Questions