基于另外两个对象创建一个对象

Create an object based on 2 others

本文关键字:两个 对象 创建 一个对象 于另外      更新时间:2023-09-26

可能重复:
如何动态合并两个JavaScript对象的属性?

我有两个这样定义的对象a和b:

a = { 
  a: 1, 
  af: function() { console.log(this.a) }, 
};
b = { 
  b: 2, 
  bf: function() { console.log(this.b) },
};

我现在想要的是创建另一个对象,它将获得a和b的属性,如下所示:

c = { 
  a: 1, 
  af: function() { console.log(this.a) },
  b: 2, 
  bf: function() { console.log(this.b) },
}

请注意,a和b需要保持不变。

知道怎么做吗?

您可以对a和b执行for in循环,并将所有hasOwn属性复制到一个新对象。

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];

演示


或者,如果你碰巧在使用jQuery,你可以这样做:

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 ) );
            });
        }
    };
}

所以现在我们可以像一样

var c = Object.create( null );
extend( c ).with( a );
extend( c ).with( b );

免责声明:提供的代码假设我们处于ES5或ES5屏蔽环境中

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]; } }

您可以将此功能抽象为自己的"扩展"功能,类似于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);