ES6 Spread operator to vanilla Javascript

1375 views javascript
5

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

answered question

ES6 === Vanilla. Do you mean ES5 by chance?

1 Answer

3

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.

posted this

Have an answer?

JD

Please login first before posting an answer.