我需要能够在运行时合并两个(非常简单的)JavaScript对象。例如,我想要:
var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }
obj1.merge(obj2);
//obj1 now has three properties: food, car, and animal
有没有内置的方法可以做到这一点?我不需要递归,也不需要合并函数,只需要在平面对象上使用方法。
我需要能够在运行时合并两个(非常简单的)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};
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-proposal-object-rest-spread插件才能使其工作(该插件包含在@babel/preset-env
中,ES2018)。
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;
}
Object.assign(obj1, obj2)
可能更好,因为let merged = {...obj1, ...obj2}
会创建一个新对象,并将obj1
和obj2
的属性复制到其中,这对于大型对象可能非常昂贵。assign方法也修改了obj1
,符合问题中预期的行为。 - SePeFjQuery也为此提供了一个实用工具: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.
jQuery.extend(true,settings,override)
,如果设置中的属性包含一个对象,而覆盖只有该对象的一部分,则此设置非常重要。 深度设置不会删除不匹配的属性,而是仅在存在的情况下更新。 默认值为false。 - vol7ronHarmony ECMAScript 2015(ES6)规定了Object.assign
函数,可以实现此功能。
Object.assign(obj1, obj2);
Object.assign
的覆盖范围相当不错:http://kangax.github.io/compat-table/es6/#test-Object_static_methods_Object.assign - brass monkeyObject.assign({}, obj1, obj2)
返回一个新对象。 - Duvrai我在谷歌上搜索合并对象属性的代码,最终来到了这里。然而,由于没有递归合并的代码,我自己写了一个。(顺便说一句,也许jQuery的extend方法是递归的?)无论如何,希望其他人也会发现它有用。
(现在代码不再使用Object.prototype
:)
/*
* Recursively merge properties of two objects
*/
function MergeRecursive(obj1, obj2) {
for (var p in obj2) {
try {
// Property in destination object set; update its value.
if ( obj2[p].constructor==Object ) {
obj1[p] = MergeRecursive(obj1[p], obj2[p]);
} else {
obj1[p] = obj2[p];
}
} catch(e) {
// Property in destination object not set; create it and set its value.
obj1[p] = obj2[p];
}
}
return obj1;
}
o1 = { a : 1,
b : 2,
c : {
ca : 1,
cb : 2,
cc : {
cca : 100,
ccb : 200 } } };
o2 = { a : 10,
c : {
ca : 10,
cb : 20,
cc : {
cca : 101,
ccb : 202 } } };
o3 = MergeRecursive(o1, o2);
生成类似 o3 的对象
o3 = { a : 10,
b : 2,
c : {
ca : 10,
cb : 20,
cc : {
cca : 101,
ccb : 202 } } };
`var data = {};
var json = '{"a": "1", "__proto__": { "x": "pwnd" }}';
MergeRecursive(data, JSON.parse(json));
var data2 = {};
console.log(data2.x);`
- undefined请注意,underscore.js
的extend
-方法可以在一行代码中完成此操作:
_.extend({name : 'moe'}, {age : 50});
=> {name : 'moe', age : 50}
_({}).extend(obj1, obj2);
- Abe Voelker与jQuery extend()类似,在AngularJS中也有相同的函数:
// Merge the 'options' object into the 'settings' object
var settings = {validate: false, limit: 5, name: "foo"};
var options = {validate: true, name: "bar"};
angular.extend(settings, options);
今天我需要合并对象,这个问题(以及答案)帮了我很多忙。我尝试了一些答案,但没有一个符合我的需求,所以我结合了一些答案,加入了一些自己的东西,得出了一个新的合并函数。以下是它:
var merge = function() {
var obj = {},
i = 0,
il = arguments.length,
key;
for (; i < il; i++) {
for (key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
obj[key] = arguments[i][key];
}
}
}
return obj;
};
一些示例用法:
var t1 = {
key1: 1,
key2: "test",
key3: [5, 2, 76, 21]
};
var t2 = {
key1: {
ik1: "hello",
ik2: "world",
ik3: 3
}
};
var t3 = {
key2: 3,
key3: {
t1: 1,
t2: 2,
t3: {
a1: 1,
a2: 3,
a4: [21, 3, 42, "asd"]
}
}
};
console.log(merge(t1, t2));
console.log(merge(t1, t3));
console.log(merge(t2, t3));
console.log(merge(t1, t2, t3));
console.log(merge({}, t1, { key1: 1 }));
你可以使用对象展开语法来实现这个目标。它是ES2018及更高版本的一部分。
const obj1 = { food: 'pizza', car: 'ford' };
const obj2 = { animal: 'dog' };
const obj3 = { ...obj1, ...obj2 };
console.log(obj3);
为避免复制整个原型链的属性,应修改给出的解决方案,在for..in
循环中添加检查语句source.hasOwnProperty(property)
后再进行赋值,这在大多数情况下是不需要的...
Object.assign
方法是ECMAScript 2015(ES6)标准的一部分,正是你所需要的。(IE
不支持)
var clone = Object.assign({}, obj);
Object.assign() 方法被用来将一个或多个源对象的所有可枚举属性值复制到目标对象中。
支持旧版浏览器的polyfill(填充):
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
nextSource = Object(nextSource);
var keysArray = Object.keys(nextSource);
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}
var obj2 = { animal: 'dog', food: 'bone' };
,则合并结果将为{ food: 'bone', car: 'ford', animal: 'dog' }
。如果您正在处理“嵌套数据”,并希望进行“深度合并”,那么请查找提到“深度合并”或“递归”的答案。如果您有数组值,请使用github “TehShrike/deepmerge”的“arrayMerge”选项,如此处所述。 - ToolmakerSteve