How to make a shallow copy of an Object in Javascript

/ August 31, 2017/ Javascript

Since a Javascript Object is a reference type is it not possible to make a copy by just doing newObject = oldObject because changes in one Object will affect the other. For example:

var originalObject = {
    fn: function(){console.log("Hola amigos");},
    string: "100",
    number: 100,
}

var newObject = originalObject;

newObject.fn = "I am not a function anymore 🙁 )";

console.log(originalObject.fn); // Prints "I am not a function anymore"

But if instead we use Object.assign({},) a shallow copy of our object will be created:

var originalObject = {
    fn: function(){console.log("Hola amigos");},
    string: "100",
    number: 100,
}

var newObject = Object.assign({},originalObject); 

newObject.fn = "I am not a function anymore 🙁 )";

console.log(originalObject.fn); // I am a function 🙂
console.log(newObject.fn); // I am not a function 🙁
Ad:

Object.assign and Internet Explorer

Sadly, Object.assign is not supported by Internet Explorer. If you really need to support it, you can use this polyfill:

if (!Object.assign) {
  Object.defineProperty(Object, 'assign', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(target) {
      'use strict';
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert first argument to object');
      }

      var to = Object(target);
      for (var i = 1; i < arguments.length; i++) {
        var nextSource = arguments[i];
        if (nextSource === undefined || nextSource === null) {
          continue;
        }
        nextSource = Object(nextSource);

        var keysArray = Object.keys(Object(nextSource));
        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
          var nextKey = keysArray[nextIndex];
          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
          if (desc !== undefined && desc.enumerable) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
      return to;
    }
  });
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
*
*