I have a defaultObject like that:
var default = {
abc: \"123\",
def: \"456\",
ghi: {
jkl: \"789\",
mno: \"012\"
}
};
For those who don't use jQuery, here comes a vanilla-js solution.
Solution:
function extend (target) {
for(var i=1; i
Compressed (with Closure Compiler):
Only 199 characters!
var extend=function e(c){for(var d=1;d
How to use:
extend(target, obj1, obj2); // returns target
If you only want to merge, use
var merged = extend({}, obj1, obj2);
Features:
target
's properties, if extended, are replaced by new ones, and the original ones are not modified.Examples:
extend({}, {a:1}, {a:2}); // {a:2}
extend({}, {a:1}, {b:2}); // {a:1, b:2}
extend({}, {a: {b:1}}, {a: {b:2}}); // {a: {b:2}}
extend({}, {a: {b:1}}, {a: {c:2}}); // {a: {b:2, c:2}}
extend({}, {a: {a:1}}, {a: {b:2}}, {a: 'whatever non object'});
// {a: "whatever non object"}
extend({}, {a: {a:1}}, {a: {b:2}}, {a: 'whatever non object'}, {a: {c:3}},{a: {d:4}});
// {a: {c:3, d:4}}
Warning:
Be aware that if browser is not clever enough, it could be trapped in an infinite loop:
var obj1={},
obj2={};
obj1.me=obj1;
obj2.me=obj2;
extend({},obj1,obj2);
If the browser is clever enough, it can throw an error, or return {me: undefined}
, or whatever.
Note that this warning also applies if you use jQuery's $.extend
.