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

新手上路,请多包涵

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

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

obj1.merge(obj2);

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

有没有内置的方法来做到这一点?我不需要递归,也不需要合并函数,只需要平面对象上的方法。

原文由 JC Grubbs 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 710
2 个回答

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

原文由 John Millikin 发布,翻译遵循 CC BY-SA 4.0 许可协议

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.

原文由 Avdi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题