How do you combine two objects in Javascript?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How can I merge properties of two JavaScript objects dynamically?
如果我有两个javascript对象,用作键值对的列表:
1 2 | var a = {a:1}; var b = {b:2}; |
将它们组合成包含两个属性的第三个对象的最有效方法是什么?
1 | var c = {a:1, b:2}; |
我不介意在这个过程中是否同时修改了
你可以简单地做到这一点:
1 2 3 4 5 6 7 | var c = {}; for (var key in a) { c[key] = a[key]; } for (var key in b) { c[key] = b[key]; } |
如果要进行深度合并(假设不想复制函数和原型),可以使用以下方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | function goclone(source) { if (Object.prototype.toString.call(source)==='[object Array]') { var clone = []; for (var i=0; i<source.length; i++) { if (source[i]) clone[i] = goclone(source[i]); } return clone; } else if (typeof(source)=="object") { var clone = {}; for (var prop in source) { if (source[prop]) { var firstChar = prop.charAt(0); clone[prop] = goclone(source[prop]); } } return clone; } else { return source; } } var c = {}; for (var key in a) { c[key] = goclone(a[key]); } for (var key in b) { c[key] = goclone(b[key]); } |
但坦率地说,我从未见过在JavaScript中进行深度合并的用途…