Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending object's properties without overwriting them

I'm trying to extend the keys/values in target object (with the keys/values) from source object, but without overwriting existing keys/values in the target object. Meaning:

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

Interestingly, I found Object.assign(obj1,obj2);, but it overwrites the keys/values.

I need to not overwrite them, if existent and add them if nonexistent.

Please help in plain JavaScript.

like image 661
tonycor nikolauos Avatar asked Oct 30 '22 14:10

tonycor nikolauos


2 Answers

Just a simple loop. If you only want enumerable own properties, then:

Object.keys(obj2).forEach(function(key) {
    if (!(key in obj1)) {
        obj1[key] = obj2[key];
    }
});

If you want all enumerable properties:

var key;
for (key in obj2) {
    if (!(key in obj1)) {
        obj1[key] = obj2[key];
    }
}

The key (no pun) bit there is the in operator, which tells you whether an object has a property (of its own, or via inheritance).

There's also Object.prototype.hasOwnProperty which would tell you only if the object has its own (not inherited) property with a given name:

Object.keys(obj2).forEach(function(key) {
    if (!obj1.hasOwnProperty(key)) {
        obj1[key] = obj2[key];
    }
});

More:

  • in operator
  • hasOwnProperty
like image 155
T.J. Crowder Avatar answered Nov 09 '22 07:11

T.J. Crowder


There is no such built in functions available in JS to do that for you.

You have to write your own logic to do that,

var x = {a:10};
var y = {a:5, b: 20};

merge(x,y);

function merge(objSrc, objTarget){
 return Object.keys(objTarget).reduce(function(src, prop){
   if(!src.hasOwnProperty(prop)) src[prop] = objTarget[prop];
   return src;
 }, objSrc);
}

console.log(x); {a:10, b:20}

P.S The above code would do a merge over enumerable own properties since Object.keys() would return the same.

like image 43
Rajaprabhu Aravindasamy Avatar answered Nov 09 '22 07:11

Rajaprabhu Aravindasamy