How can I merge 2 object in javascript? e.g. if objB.a2 not exist then objB.a2 = objA.a2
objA = {
a1:
a2:
a3:
}
objB = {
a1:
a3:
}
for (var k in objB) {
if (typeof objB[k] === 'undefined') {
// objB[k] =
}
}
How can I merge 2 object in javascript? e.g. if objB.a2 not exist then objB.a2 = objA.a2
objA = {
a1:
a2:
a3:
}
objB = {
a1:
a3:
}
for (var k in objB) {
if (typeof objB[k] === 'undefined') {
// objB[k] =
}
}
With jQuery you can just do this:
$.extend(objB, objA);
This will merge all the properties of objA
into objB
. To merge them into a whole new object do this:
var objC = {};
$.extend(objC, objA, objB);
Without jQuery you can do it like this (this will add objA
's properties to objB
):
for (var attrname in objA) { objB[attrname] = objA[attrname]; }
For more details see: How can I merge properties of two JavaScript objects dynamically?
Try this
function merge(obj1,obj2){
var obj3 = {}, prop;
for (prop in obj1) {
obj3[prop] = obj1[prop];
}
for (prop in obj2) {
obj3[prop] = obj2[prop];
}
return obj3;
}
merge(obj1, obj2);
You can use _.extend() method from Underscore.JS as well. See details in http://underscorejs.org/#extend
It is a tiny and powerful JavaScript library of helper functions.
If you want to receive a NEW object with properties of both objA and objB i suppose you could use a function like:
objA = {
a1: 1,
a2: 2,
a3: 3
}
objB = {
a1: 4,
a4: 5
}
function merge(objA, objB){
var o = {};
for (prop in objA) //copy objA props to new object
o[prop] = objA[prop];
for (prop in objB) { //copy objB props to new object
if (o[prop] === undefined) //check if the property name is used already
o[prop] = objB[prop]; // if the prop name is not used - assign it
}
return o;
};
console.log(merge(objA, objB)); //check the result!