提问者:小点点

如何动态合并两个JavaScript对象的属性?


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

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

obj1.merge(obj2);

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

有没有人有这样的脚本或者知道这样做的内置方式? 我不需要递归,也不需要合并函数,只是平面对象上的方法。


共3个答案

匿名用户

ECMAScript 2018标准方法

您将使用对象扩展:

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

merged现在是obj1obj2的联合。 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-transform-object-rest-spread插件来使其工作。

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;
}

匿名用户

jQuery还有一个用于此的实用程序:http://api.jQuery.com/jQuery.extend/。

摘自jQuery文档:

// Merge options object into settings object
var settings = { validate: false, limit: 5, name: "foo" };
var options  = { validate: true, name: "bar" };
jQuery.extend(settings, options);

// Now the content of settings object is the following:
// { validate: true, limit: 5, name: "bar" }

上述代码将改变名为settings的现有对象。

如果要在不修改任何一个参数的情况下创建新对象,请使用以下命令:

var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };

/* Merge defaults and options, without modifying defaults */
var settings = $.extend({}, defaults, options);

// The content of settings variable is now the following:
// {validate: true, limit: 5, name: "bar"}
// The 'defaults' and 'options' variables remained the same.

匿名用户

Harmony ECMAScript 2015(ES6)指定了object.assign,它将执行此操作。

Object.assign(obj1, obj2);

当前的浏览器支持正在变得更好,但是如果您正在为没有支持的浏览器开发,您可以使用Polyfill。