Alex Rivera | Logout

javascript - Add property to object literal and return

Asked 2011-12-21T22:38:07.250
13

I have object literal what I consider as base object:

var obj = {
   key1   : 'value1',
   key2   : 'value2'
}

and would like to use this object and pass it to function with extention like

myFunction( obj + { key3 : 'value3' } );

// param became:
{
   key1   : 'value1',
   key2   : 'value2',
   key3   : 'value3'
}

or

myFunction( obj + { key2 : 'new value2' } );

// param became:
{
   key1   : 'value1',
   key2   : 'new value2'
}

+ operator is not correct for it. How I can do it? Is it a way ?

EDIT: Do you want to permanently alter obj? - No, I would like to able to reuse it for next call as base.

Edit
Report

1 Answer

0

You could create a function that extends objects nondestructively (not "extend", really, just make a new object from another one), for example:

var oldObj = {name: 'foo'};

function extendNonDestructive(src, newProps) {
  function F() {} F.prototype = src;
  var newObj = new F;
  for (var p in newProps) {
    if (newProps.hasOwnProperty(p)) {
      newObj[p] = newProps[p]
    }
  }
  return newObj
}

var newObj = extendNonDestructive(oldObj, {lastName: 'bar'}); // Doesn't touch oldObj

Note: You might be interested in Object.create which is way more flexible than the little "function F() {}; F.prototype = src;" in my code, but it's ES5+.

answered 2011-12-21T23:27:50.730

Your Answer