Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an object based on 2 others [duplicate]

Tags:

javascript

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 ?

like image 633
Nicolas BADIA Avatar asked Jan 18 '12 16:01

Nicolas BADIA


3 Answers

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);
like image 132
Adam Rackis Avatar answered Sep 20 '22 17:09

Adam Rackis


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 !

like image 39
jAndy Avatar answered Sep 20 '22 17:09

jAndy


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);
like image 37
maerics Avatar answered Sep 20 '22 17:09

maerics