Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Spread operator to vanilla Javascript

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];
};
like image 487
Afshin Ghazi Avatar asked Sep 16 '18 18:09

Afshin Ghazi


2 Answers

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.

like image 184
Michał Perłakowski Avatar answered Oct 26 '22 23:10

Michał Perłakowski


Since you want the syntax for ES5 here is a polyfill for Object.assing() (source: MDN)

   

// we first set the Object.assign function to null to show that the polyfill works
Object.assign = null;

// start polyfill

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
  });
}

// end polyfill


   // example, to test the polyfill:

const object1 = {
  a: 1,
  b: 2,
  c: 3
};

const object2 = Object.assign({c: 4, d: 5}, object1);

console.log(object2.c, object2.d);
// expected output: 3 5
like image 29
Willem van der Veen Avatar answered Oct 27 '22 00:10

Willem van der Veen