1

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] = 
  }
}
m59
  • 43,214
  • 14
  • 119
  • 136
  • First: You have created an incorrect Javascript Object. Second you could simply iterate like you already do. Check if the key `k` exists in A when it doesnt exist in objB. – David Snabel Feb 24 '15 at 08:02
  • possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – David Snabel Feb 24 '15 at 08:05

4 Answers4

1

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?

Community
  • 1
  • 1
winhowes
  • 7,845
  • 5
  • 28
  • 39
0

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);
Vaibhav
  • 1,479
  • 8
  • 13
0

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.

Max Zuber
  • 1,217
  • 10
  • 16
0

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!
Greg
  • 1,851
  • 2
  • 19
  • 21