1

2 つの連想配列またはオブジェクトを 1 つに結合する組み込みメソッドを探しています。それが違いを生む場合は、Adobe AirでWebkitを使用します。しかし、基本的には、2 つのオブジェクトまたは連想配列があります。

var obj1 = { prop1: "something", prop2 "anotherthing" };
var obj2 = { prop3: "somethingelse" };

そして、それらをマージして、上記の 2 つのオブジェクトのキーと値をすべて組み合わせたオブジェクトを作成したいと考えています。

var obj3 = obj1.merge( obj2 ); //something similar to array's concat maybe?

alert(obj3.prop1); //alerts "something"
alert(obj3.prop2); //allerts "anotherthing"
alert(obj3.prop3); //alerts "somethingelse"

これを行う組み込み関数はありますか、それとも手動で行う必要がありますか?

4

3 に答える 3

5

トリプティクが言ったように、彼のサンプルコード(彼がそれを編集するまでは危険で間違っていた)を除いて。次のようなもう少し良いものが良いでしょう。

mylib = mylib || {};
//take objects a and b, and return a new merged object o;
mylib.merge = function(a, b) {

  var i, o = {};
  for(i in a) {
      if(a.hasOwnProperty(i)){
          o[i]=a[i];
      }
  }
  for(i in b) {
      if(b.hasOwnProperty(i)){
          o[i]=b[i];
      }
  }

  return o;

}
//take objects a and b, and modify object a to have b's properties
mylib.augment = function(a, b) {
  var i;
  for(i in b) {
      if(b.hasOwnProperty(i)){
          a[i]=b[i];
      }
  }
  return a;
}

再編集:凶暴。ディープコピーはこれとは異なり、直交関数ですが、これが私の個人的なディープコピー関数です。

   function clone(o) {
    var t,i;
    if (o === undefined) {
        return undefined;
    }
    if (o === null) {
        return null;
    }
    if (o instanceof Function) {
        return o;
    }
    if (! (o instanceof Object)) {
        return o;
    } else {
        t = {};
        for (i in o) {
            /* jslint complains about this, it's correct in this case. I think. */
            t[i] = clone(o[i]);
        }
        return t;
    }
   }
于 2009-06-11T03:24:53.947 に答える
4

Triptychの代替実装(これは基本的にPrototypeのextendメソッドと同じです)は次のとおりです。

/** returns object with properties of both object1 and object2. 
  *  if a collision occurs, properties of object1 take priority
  */
function merge(object1,object2) {
    var retObj = {};
    for (prop in object2){
        retObj[prop] = object2[prop];
    }
    for (prop in object1){
        retObj[prop] = object1[prop];
    }
    return retObj;
}

これはObjectのプロトタイプを変更しないため、重大な欠点はありません。

于 2009-06-11T03:24:40.907 に答える
4

組み込みメソッドはありません。いくつかのライブラリは、あなたが説明したことを行う方法を提供します。

自分で書くのは簡単です:

var merge = function(dest, source){
    // This will resolve conflicts by using the source object's properties
    for (prop in source){
        dest[prop] = source[prop];
    }
}

// Use like so
merge(obj1, obj2);

編集: Object.prototype を変更することはなくなりました。これは危険であり、一般的に眉をひそめます。

于 2009-06-11T03:08:10.207 に答える