javascript-objects - JavaScript object - 如何动态地合并两个JavaScript对象的属性?

Js object add property / javascript

我需要在运行时能够合并两个(非常简单的)JavaScript对象。例如,我想。

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

obj1.merge(obj2);

// obj1现在具有三个属性:食物,汽车和动物

4 revs, 4 users 64%



Answer #1
var realMerge = function (to, from) {

    for (n in from) {

        if (typeof to[n] != 'object') {
            to[n] = from[n];
        } else if (typeof from[n] == 'object') {
            to[n] = realMerge(to[n], from[n]);
        }
    }
    return to;
};
var merged = realMerge(obj1, obj2);