Search code examples
javascriptpolyfillsbabel-polyfill

Javascript - Is there a cdn link for the object spread polyfill?


I'm searching a polyfill for the object spread operator in javascript. Does anyone have a cdn link or if not a way to do it with es5 javascript?

var i = {
  test: 123,
  test1: 5234
}

var b = {
  ...i,
  test3: 243
}

Solution

  • No, it is impossible. Object spread is syntax, so it cannot be polyfilled. Only new objects and methods can be polyfilled, but not new syntax.

    However, you can transpile the code using Babel: http://babeljs.io/

    "use strict";
    
    function _objectSpread(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
          ownKeys = ownKeys.concat(
            Object.getOwnPropertySymbols(source).filter(function(sym) {
              return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            })
          );
        }
        ownKeys.forEach(function(key) {
          _defineProperty(target, key, source[key]);
        });
      }
      return target;
    }
    
    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, {
          value: value,
          enumerable: true,
          configurable: true,
          writable: true
        });
      } else {
        obj[key] = value;
      }
      return obj;
    }
    
    var i = {
      test: 123,
      test1: 5234
    };
    
    var b = _objectSpread({}, i, {
      test3: 243
    });
    

    Ugly, but it'll work, and can be done automatically.

    For this particular case, you can polyfill Object.assign and use:

    var b = Object.assign({}, i, { test3: 243 });