Hugh Phan Hugh Phan - 4 years ago 105
Javascript Question

Combining two objects but if first object already has a property ignore the property in second object

Given two objects, "extend" adds properties from the 2nd object to the 1st object.

Notes:


  • Add any keys that are not in the 1st object.

  • If the 1st object already has a given key, ignore it (do not overwrite the property value).

  • Do not modify the 2nd object at all.

    var obj1 = {
    a: 1,
    b: 2
    };
    var obj2 = {
    b: 4,
    c: 3
    };

    extend(obj1, obj2);

    console.log(obj1); // --> {a: 1, b: 2, c: 3}



I was able to get this far :

function extend(obj1, obj2) {
for (var key in obj2) {
obj1[key] = obj2[key];
}
return obj1;
}


which logged:

{a: 1, b: 4, c: 3}


I've been cracking my skull trying to figure this out for the passed two days or so. Tried googling and everything. Thanks in advance :)

Answer Source

Basically, you just need to iterate through each key on the 2nd object and see if the first object has that key or not.

The iteration can be done using a for..in loop, as you know. The part your're missing is how to check if an object already has a given property. That's what hasOwnProperty is for.

function extend(obj1, obj2) {
  // Iterate over every (enumerable) key in obj2
  for (var key in obj2) {
    // If obj1 does not have a key by this name,
    // add it to obj1
    if (!obj1.hasOwnProperty(key)) {
      obj1[key] = obj2[key];
    }
  }
}

var obj1 = {
  a: 1,
  b: 2
};
var obj2 = {
  b: 4,
  c: 3
};

extend(obj1, obj2);
console.log(obj1); // --> {a: 1, b: 2, c: 3}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download