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

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

obj1.merge(obj2);

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

是否有一种内置的方法来实现这一点?我不需要递归,也不需要合并函数,只需要平面对象上的方法。


当前回答

值得一提的是,140byt.es集合的版本在最小空间内解决了这一任务,值得一试:

代码:

function m(a,b,c){for(c in b)b.hasOwnProperty(c)&&((typeof a[c])[0]=='o'?m(a[c],b[c]):a[c]=b[c])}

用途:

m(obj1,obj2);

这是原始的Gist。

其他回答

GitHub上有一个名为deepmmerge的库:这似乎正在引起一些关注。它是一个独立的,可以通过npm和bower包管理器获得。

我倾向于使用或改进这一点,而不是复制粘贴答案中的代码。

如果有人正在使用Google闭包库:

goog.require('goog.object');
var a = {'a': 1, 'b': 2};
var b = {'b': 3, 'c': 4};
goog.object.extend(a, b);
// Now object a == {'a': 1, 'b': 3, 'c': 4};

数组存在类似的助手函数:

var a = [1, 2];
var b = [3, 4];
goog.array.extend(a, b); // Extends array 'a'
goog.array.concat(a, b); // Returns concatenation of array 'a' and 'b'

最好的方法是使用Object.defineProperty添加一个不可枚举的适当属性。

通过这种方式,您仍然可以迭代对象财产,而无需使用Object.prototype.extend创建属性时新创建的“extend”。

希望这有助于:

Object.defineProperty(Object.prototype, "extend", {
    enumerable: false,
    value: function(from) {
        var props = Object.getOwnPropertyNames(from);
        var dest = this;
        props.forEach(function(name) {
            if (name in dest) {
                var destination = Object.getOwnPropertyDescriptor(from, name);
                Object.defineProperty(dest, name, destination);
            }
        });
        return this;
    }
});

一旦你做到了这一点,你就可以做到:

var obj = {
    name: 'stack',
    finish: 'overflow'
}
var replacement = {
    name: 'stock'
};

obj.extend(replacement);

我刚刚在这里写了一篇博文:http://onemoredigit.com/post/1527191998/extending-objects-in-node-js

这会将obj合并为“默认”def。obj优先于两者中存在的任何对象,因为obj被复制到def中。还要注意,这是递归的。

function mergeObjs(def, obj) {
    if (typeof obj == 'undefined') {
        return def;
    } else if (typeof def == 'undefined') {
        return obj;
    }
    for (var i in obj) {
        if (obj[i] != null && obj[i].constructor == Object) {
            def[i] = mergeObjs(def[i], obj[i]);
        } else {
            def[i] = obj[i];
        }
    }
    return def;
}

a = {x : {y : [123]}}
b = {x : {z : 123}}
console.log(mergeObjs(a, b));
// {x: {y : [123], z : 123}}

函数扩展(o,o1,o2){如果(!(o instanceof Object))o={};副本(o,o1);如果(o2)副本(o,o2)函数isObject(obj){var type=Object.protype.toString.call(obj);return obj===对象(obj)&&type!='[object Array]'&&type!='[object函数]';};功能副本(a,b){//将o2复制到ofor(b中的var键)if(b.hasOwnProperty(键)){if(isObject(b[key])){if(!isObject(a[key]))a[key]=Object.assign({},b[key]);其他副本(a[key],b[key])}其他的a[key]=b[key];}}返回o;};变量o1={a:{foo:1},b:1},o2={a:{bar:2},b:[1],c:()=>{}},newMerged=扩展({},o1,o2);console.log(newMerged)控制台日志(o1)控制台日志(o2)