如何在Javascript / JQuery中将对象的属性合并到一个对象中?
我有以下两个对象,obj& OBJ2:
var obj = {
a: '1',
b: '2'
}
var obj2 = {
c: '3',
d: '4'
}
我想把它们合并成这样的东西:
var obj = {
a: '1',
b: '2',
c: '3',
d: '4'
}
任何帮助将不胜感激!谢谢!
答案 0 :(得分:1)
var obj = $.extend({},obj,obj2);
答案 1 :(得分:1)
答案 2 :(得分:0)
<强> CODE:
强>
function merge(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}
var obj = {
a: '1',
b: '2'
}
var obj2 = {
c: '3',
d: '4'
}
alert(merge(obj,obj2)["a"]);
alert(merge(obj,obj2)["b"]);
alert(merge(obj,obj2)["c"]);
alert(merge(obj,obj2)["d"]);
答案 3 :(得分:0)
您可以使用缩小来合并多个对象:
function merge() {
return [].reduce.call(arguments, function(a,e) {
for (var i in e) a[i] = e[i];
return a;
},{});
}
var a = {a:'a'};
var b = {b:'b'};
var c = {c:'c'};
merge(a,b,c); //=> {a:'a', b:'b', c:'c'}
答案 4 :(得分:0)
试试这个: -
var dT_1 = '{"a": "1", "b":"2"}';
var dT_2 = '{"c": "3", "d":"4"}';
var jD_1 = JSON.parse(dT_1);
var jD_2 = JSON.parse(dT_2);
var obj = $.extend({},jD_1,jD_2); // Object {a: "1", b: "2", c: "3", d: "4"}