How to make a shallow copy of an Object in Javascript

/ August 31, 2017/ Javascript

(Last Updated On: February 11, 2018) 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
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments