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

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

obj1.merge(obj2);

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

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


当前回答

我使用Object.create()来保持默认设置(使用__proto__或Object.getPrototypeOf())。

function myPlugin( settings ){
    var defaults = {
        "keyName": [ "string 1", "string 2" ]
    }
    var options = Object.create( defaults );
    for (var key in settings) { options[key] = settings[key]; }
}
myPlugin( { "keyName": ["string 3", "string 4" ] } );

这样我以后就可以一直使用“concat()”或“push()”。

var newArray = options['keyName'].concat( options.__proto__['keyName'] );

注意:为了避免重复,需要在连接之前进行hasOwnProperty检查。

其他回答

ECMAScript 2018标准方法

您可以使用对象扩散:

let merged = {...obj1, ...obj2};

merged现在是obj1和obj2的并集。obj2中的财产将覆盖obj1中的属性。

/** There's no limit to the number of objects you can merge.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = {...obj1, ...obj2, ...obj3};

这里还有此语法的MDN文档。如果您正在使用babel,则需要@babel/plugin提议对象rest spread插件才能工作(该插件包含在ES2018中的@babel/preset-env中)。

ECMAScript 2015(ES6)标准方法

/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
 *  All objects get merged into the first object. 
 *  Only the object in the first argument is mutated and returned.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);

(参见MDN JavaScript参考)


ES5及更早版本的方法

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

请注意,这将简单地将obj2的所有属性添加到obj1中,如果您仍然希望使用未修改的obj1,那么这可能不是您想要的。

如果你使用的是一个在你的原型上到处都是垃圾的框架,那么你必须通过hasOwnProperty这样的检查来获得更高的效率,但这段代码在99%的情况下都是有效的。

示例函数:

/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}

您可以在EcmaScript2016中执行以下操作

更正:这是第三阶段的建议,但它始终对我有效

const objA = {
  attrA: 'hello',
  attrB: true
}

const objB = {
  attrC: 2
}

const mergedObj = {...objA, ...objB}

对象.assign()

ECMAScript 2015(ES6)

这是一项新技术,是ECMAScript 2015(ES6)标准的一部分。这项技术的规范已经定稿,但请查看兼容性表,了解各种浏览器中的用法和实现状态。

assign()方法用于将所有可枚举自身财产的值从一个或多个源对象复制到目标对象。它将返回目标对象。

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, target object itself is changed.

您可以通过以下方法合并对象

var obj1={food:‘pizza‘,car:‘ford‘};var obj2={animal:‘dog‘};var result=合并对象([obj1,obj2]);console.log(结果);document.write(“result:<pre>”+JSON.stringify(result,0,3)+“</pre>”);函数mergeObjects(objectArray){if(objectArray.length){var b=“”,i=-1;while(objectArray[++i]){var str=JSON.stringify(objectArray[i]);b+=字符串长度(1,字符串长度-1);如果(objectArray[i+1])b+=“,”;}返回JSON.parse(“{”+b+“}”);}返回{};}

有三种方法可以做到这一点:-

方法1:-

// using spread ...
    let obj1 = {
        ...obj2
    };

方法2:-

// using  Object.assign() method
let obj1 = Object.assign({}, obj2);

方法3:-

// using JSON
let obj1 = JSON.parse(JSON.stringify(obj2));