0

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
}
Ed Bangga
  • 12,879
  • 4
  • 16
  • 30
ProV
  • 251
  • 1
  • 4
  • 14

2 Answers2

4

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 });
Snow
  • 3,820
  • 3
  • 13
  • 39
  • Oh, thanks for this information. I've been looking for some time now and couldn't find an answear. Unfortunately I don't using webpack to transpile the code, so I have to use the object assign. – ProV Jun 25 '19 at 07:12
2

The spread/rest operator was not valid syntax previously. You will need to transpile that syntax to something that is valid in order to use it.

Goblinlord
  • 3,290
  • 1
  • 20
  • 24