2009-06-11 57 views
1

我在找一個內置的方法,它將兩個關聯數組或對象合併爲一個。在Adobe Air中使用webkit如果有所作爲。但基本上我有兩個對象或關聯數組,如果你會:是否有內置方法將兩個對象的屬性合併到一個對象中?

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

,我想要做的合併它們,並創建具有以上所有的兩個對象的組合鍵和值的對象:

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" 

任何內置的功能,這樣做還是我必須手動執行它?

回答

5

像tryptych說,除了他的示例代碼(是危險的和錯誤的,直到他編輯它)。更像下面的東西會更好。

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

編輯re:兇猛。深拷貝是一個不同的,正交的功能,但只爲你,這是我的個人深層複製功能

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; 
    } 
    } 
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,這是危險的,通常令人難以接受的。

+3

請注意這個實現。如果代碼中的任何位置都有for(x in obj)循環,for循環將遍歷合併函數,除非您明確地在所有循環中測試該循環。這可能不是你想要的。 – Breton 2009-06-11 03:14:11

+0

這很糟糕,純JavaScript與大對象會很慢。太糟糕了,它不存在。有意義有這樣的事情不對吧/ – 2009-06-11 03:15:10

4

一種替代實施三聯的(這是基本相同Prototype的延伸方法)是:

/** 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; 
} 

這並不修改對象的原型,因此不具有這不是微不足道的缺點。

相關問題