Possible Duplicate:
How can I merge properties of two JavaScript objects dynamically?
I have two objects a and b defined like this:
a = {
a: 1,
af: function() { console.log(this.a) },
};
b = {
b: 2,
bf: function() { console.log(this.b) },
};
What I want now is to create another object which will get the properties of a and b, like this:
c = {
a: 1,
af: function() { console.log(this.a) },
b: 2,
bf: function() { console.log(this.b) },
}
Note that a and b need to stay the same.
Any idea of how to do this ?
You could do a for in loop for both a and b, and copy all hasOwn
properties to a new object.
var c = {};
for (var p in a)
if(a.hasOwnProperty(p))
c[p] = a[p];
for (var p in b)
if(b.hasOwnProperty(p))
c[p] = b[p];
DEMO
Or, if you happen to be using jQuery, you could do:
var c = $.extend({}, a, b);
var desc = Object.getOwnPropertyDescriptor,
props = Object.getOwnPropertyNames,
define = Object.defineProperty;
function extend( target ) {
return {
with: function( source ) {
props( source ).forEach(function( key ) {
define( target, key, desc( source, key ) );
});
}
};
}
So now we can go like
var c = Object.create( null );
extend( c ).with( a );
extend( c ).with( b );
Disclaimer: the provided codes assume we are in a ES5 or ES5 shimed environment !
var i, c={};
for (i in a) { if (a.hasOwnProperty(i)) { c[i] = a[i]; } }
for (i in b) { if (b.hasOwnProperty(i)) { c[i] = b[i]; } }
You can abstract this functionality into your own "extend" function similar to the one provided by jQuery:
function extend() {
var i, j, x, o=(arguments[0] || {});
for (i=1; i<arguments.length; i++) {
x = arguments[i];
for (j in x) { if (x.hasOwnProperty(j)) { o[j] = x[j]; } }
}
return o;
}
var c = extend({}, a, b);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With