How can I merge properties of two JavaScript objects dynamically?

I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:

var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }

obj1.merge(obj2);

//obj1 now has three properties: food, car, and animal

Does anyone have a script for this or know of a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.


Use:

//Takes any number of objects and returns one merged object
var objectMerge = function(){
    var out = {};
    if(!arguments.length)
        return out;
    for(var i=0; i<arguments.length; i++) {
        for(var key in arguments[i]){
            out[key] = arguments[i][key];
        }
    }
    return out;
}

It was tested with:

console.log(objectMerge({a:1, b:2}, {a:2, c:4}));

It results in:

{ a: 2, b: 2, c: 4 }

gossi's extension of David Coallier's method:

Check these two lines:

from = arguments[i];
Object.getOwnPropertyNames(from).forEach(function (name) {

One need to check "from" against null object... If for example merging an object that comes from an Ajax response, previously created on a server, an object property can have a value of "null", and in that case the above code generates an error saying:

"from" is not a valid object

So for example, wrapping the "...Object.getOwnPropertyNames(from).forEach..." function with an "if (from != null) { ... }" will prevent that error occurring.


Deep recursive merge of JSON strings and values (better implementation to Markus' answer):

Code

function mergeRecursive(obj1, obj2) {
    for (var p in obj2) {
        if( obj2.hasOwnProperty(p)){
            obj1[p] = typeof obj2[p] === 'object' ? mergeRecursive(obj1[p], obj2[p]) : obj2[p];
        }
    }
    return obj1;
}

Example:

o1 = { a:1, b:2, c:{ ca:1, cb:2, cc:{ cca:100, ccb:200 }}};
o2 = { a:10, c:{ ca:10, cb:20, cc:{ cca:101, ccb:202 }}};
mergeRecursive(o1, o2);

Output:

{ a : 10,
     b : 2,
     c : {
         ca : 10,
         cb : 20,
         cc : {
             cca : 101,
             ccb : 202
         }
     }
};
链接地址: http://www.djcxy.com/p/4698.html

上一篇: 我怎样才能显示一个JavaScript对象?

下一篇: 我如何动态合并两个JavaScript对象的属性?