我如何动态合并两个JavaScript对象的属性?
我需要能够在运行时合并两个(非常简单的)JavaScript对象。 例如,我想:
var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }
obj1.merge(obj2);
//obj1 now has three properties: food, car, and animal
有没有人有这个脚本或知道内置的方式来做到这一点? 我不需要递归,也不需要合并函数,只需要平面对象上的方法。
ECMAScript 2018标准方法
你会使用对象休息传播:
let merged = {...obj1, ...obj2};
/** 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};
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。
链接地址: http://www.djcxy.com/p/707.html上一篇: How can I merge properties of two JavaScript objects dynamically?
下一篇: How do I check if an object has a property in JavaScript?