ES6 Spread operator to vanilla Javascript

Afshin Ghazi picture Afshin Ghazi · Sep 16, 2018 · Viewed 8k times · Source

I have added a script that uses ES6 spread operator to the project that gets the params from the url. Unsure how to revert this to the normal vanilla Javascript syntax after I discovered that the project doesn't support ES6.

It's easy to take normal Javascript arrays and use the spread operator but in more complicated instances like this one I cannot make the array return the result without totally changing the script.

getQueryURLParams("country");

getQueryURLParams = function(pName) {
    var urlObject = location.search
    .slice(1)
    .split('&')
    .map(p => p.split('='))
    .reduce((obj, pair) => {
      const [key, value] = pair.map(decodeURIComponent);

      return ({ ...obj, [key]: value }) //This is the section that needs to be Vanilla Javascript
    }, {});

    return urlObject[pName];
};

Thanks to everyone for the replies. After back and forth I realized that the suggestion here that I convert the whole script to ES5 was correct since the browser only complained about that line but other items not ES5 were also problematic.

This is what I had after using ES5:

getQueryURLParams = function(pName) {


if (typeof Object.assign != 'function') {
    // Must be writable: true, enumerable: false, configurable: true
    Object.defineProperty(Object, "assign", {
      value: function assign(target, varArgs) { // .length of function is 2
        'use strict';
        if (target == null) { // TypeError if undefined or null
          throw new TypeError('Cannot convert undefined or null to object');
        }

        var to = Object(target);

        for (var index = 1; index < arguments.length; index++) {
          var nextSource = arguments[index];

          if (nextSource != null) { // Skip over if undefined or null
            for (var nextKey in nextSource) {
              // Avoid bugs when hasOwnProperty is shadowed
              if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                to[nextKey] = nextSource[nextKey];
              }
            }
          }
        }
        return to;
      },
      writable: true,
      configurable: true
    });
  }

var urlObject = location.search
.slice(1)
.split('&')
.map(function(element ) { 
    return element.split('='); 
})
.reduce(function(obj, pair) {  

  const key = pair.map(decodeURIComponent)[0];
  const value = pair.map(decodeURIComponent)[1];

  return Object.assign({}, obj, { [key]: value });
}, {});

return urlObject[pName];
};

Answer

Michał Perłakowski picture Michał Perłakowski · Sep 16, 2018

You can use Object.assign():

return Object.assign({}, obj, { [key]: value });

Demo:

const obj = { a: 1 };
const key = 'b';
const value = 2;

console.log(Object.assign({}, obj, { [key]: value }));

FWIW, the { ...obj } syntax is called "Object Rest/Spread Properties" and it's a part of ECMAScript 2018, not ECMAScript 6.