我正在寻找一种内置方法,它可以将两个关联数组或对象组合成一个。如果有所不同,请在 Adobe Air 中使用 webkit。但基本上我有两个对象或关联数组,如果你愿意的话:
var obj1 = { prop1: "something", prop2 "anotherthing" };
var obj2 = { prop3: "somethingelse" };
我想合并它们并创建一个包含上述两个对象的所有组合键和值的对象:
var obj3 = obj1.merge( obj2 ); //something similar to array's concat maybe?
alert(obj3.prop1); //alerts "something"
alert(obj3.prop2); //allerts "anotherthing"
alert(obj3.prop3); //alerts "somethingelse"
是否有任何内置函数可以执行此操作,还是我必须手动执行此操作?
最佳答案
就像 tryptych 说的,除了他的示例代码(在他编辑之前是危险和错误的)。像下面这样的东西会更好。
mylib = mylib || {};
//take objects a and b, and return a new merged object o;
mylib.merge = function(a, b) {
var i, o = {};
for(i in a) {
if(a.hasOwnProperty(i)){
o[i]=a[i];
}
}
for(i in b) {
if(b.hasOwnProperty(i)){
o[i]=b[i];
}
}
return o;
}
//take objects a and b, and modify object a to have b's properties
mylib.augment = function(a, b) {
var i;
for(i in b) {
if(b.hasOwnProperty(i)){
a[i]=b[i];
}
}
return a;
}
编辑回复:凶猛。深拷贝是一个不同的、正交的函数,但只为你,这是我个人的深拷贝函数
function clone(o) {
var t,i;
if (o === undefined) {
return undefined;
}
if (o === null) {
return null;
}
if (o instanceof Function) {
return o;
}
if (! (o instanceof Object)) {
return o;
} else {
t = {};
for (i in o) {
/* jslint complains about this, it's correct in this case. I think. */
t[i] = clone(o[i]);
}
return t;
}
}
关于javascript - 是否有内置方法可以将两个对象的属性合并到一个对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/979103/