2015-10-11 37 views
1

我需要比較兩個相同的對象(第二個具有比其他屬性更多的屬性)。比較兩個對象以覆蓋其中一個的值

我創建這個片斷這使對象的所有屬性到一個新的對象,而無需嵌套他們:

function getAllObjectProperties(source) { 
    var result = {}; 
    function getProperties(object) { 
    for (var property in object) { 
     if (typeof object[property] === 'object') getProperties(object[property]); 
     else result[property] = object[property]; 
    } 
    } 
    getProperties(source); 
    return result; 
} 

的比較函數應該是這樣的:

updateObjectProperties: function(source, target) { 
    var temp_object = self.getAllObjectProperties(source); 
    for (var property in temp_object) { 
     if (target.hasOwnProperty(property)) { 
      // target_property_of_target_element = temp_object[property]; 
     } 
     else { 
      // target_object gains new property (property nesting must be preserved) 
     } 
    } 
} 

我該怎麼辦?可能嗎?

回答

1

您可以合併對象。如果只希望在特定條件下合併對象,則可以添加條件運算符。

研究了這樣的回答: How can I merge properties of two JavaScript objects dynamically?

代碼:

var mergeObj = function (obj1, obj2) { 
    var obj3 = {}; 
    for (var attrname in obj1) { 
     obj3[attrname] = obj1[attrname]; 
    } 
    for (var attrname in obj2) { 
     obj3[attrname] = obj2[attrname]; 
    } 
    return obj3; 
} 

JS小提琴

https://jsfiddle.net/chrislewispac/8fthog46/

+0

簡單而有用!謝謝,在我的情況下,它是完美的! – Giacomo

1

將一個對象的屬性複製到另一個對象時,可以使用稱爲深度複製或淺層複製的內容。在淺拷貝中,目標對象將引用源對象的屬性,這意味着目標對象中的變化將改變源中的對象。

這裏是淺拷貝一個例子:

var source = {a: 0, b: {c: 2, d: 3}}, 
    target = {a: 1}; 

function union(target, source) { 
    Object.keys(source).filter(function (key) { 
     return !target.hasOwnProperty(key); 
    }).forEach(function (key) { 
     target[key] = source[key]; 
    }); 
} 

union(target, source); 

console.log(target); 

做一次深層副本,你可以使用JSON,但只適用,如果屬性可以在JSON表示。以下是執行深層複製的聯合功能。

function union(target, source) { 
    Object.keys(source).filter(function (key) { 
     return !target.hasOwnProperty(key); 
    }).forEach(function (key) { 
     target[key] = JSON.parse(JSON.stringify(source[key])); 
    }); 
} 
+0

我試過的功能,但我在特定情況下發生錯誤。我不太明白爲什麼,可惜我喜歡這種方法。在我的情況下,對象是json文件。 – Giacomo

+0

它在這裏工作,所以我不知道什麼是錯的。 – Waterscroll