我需要能够在运行时合并两个(非常简单的)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};
/** 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.
该 和谐ECMAScript 2015(ES6) 指定 Object.assign
这会做到这一点。
Object.assign(obj1, obj2);
我用google搜索代码来合并对象属性,最后来到这里。但是由于没有任何递归合并的代码,我自己写了。 (也许jQuery扩展是递归BTW?)无论如何,希望其他人也会觉得它很有用。
(现在代码不使用 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 } } };
注意 underscore.js
的 extend
-方法 这是一个单线程:
_.extend({name : 'moe'}, {age : 50});
=> {name : 'moe', age : 50}
与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 }));
您可以使用 对象传播属性 - 目前是第3阶段ECMAScript提案。
const obj1 = { food: 'pizza', car: 'ford' };
const obj2 = { animal: 'dog' };
const obj3 = { ...obj1, ...obj2 };
console.log(obj3);
应修改给定的解决方案以进行检查 source.hasOwnProperty(property)
在里面 for..in
在分配之前循环 - 否则,你最终会复制整个原型链的属性,这很少需要...
一个 Object.assign
method是ECMAScript 2015(ES6)标准的一部分,完全符合您的要求。 (IE
不支持)
var clone = Object.assign({}, obj);
Object.assign()方法用于将所有可枚举的自有属性的值从一个或多个源对象复制到目标对象。
该 填充工具 支持旧浏览器:
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;
}
});
}