I recently incorporated a script into my project that utilizes the ES6 spread operator to extract parameters from the URL. However, I encountered an issue when I realized that the project does not support ES6 syntax.
While it is straightforward to apply the spread operator on regular Javascript arrays, in more complex scenarios like this one, converting the array to return the desired result without altering the entire script poses a challenge.
getQueryURLParams("country");
getQueryURLParams = function(pName) {
var urlObject = location.search
.slice(1)
.split('&')
.map(function(p) { return p.split('='); })
.reduce(function(obj, pair) {
const key = decodeURIComponent(pair[0]);
const value = decodeURIComponent(pair[1]);
// This is the part that needs to be converted to Vanilla Javascript
return (Object.assign({}, obj, {[key]: value}));
}, {});
return urlObject[pName];
};
I appreciate all the responses provided. Upon further consideration, I concluded that transitioning the entire script to ES5 was necessary since some other non-ES5 elements were also causing issues alongside that specific line.
This is how the script looked after converting it to ES5:
getQueryURLParams = function(pName) {
if (typeof Object.assign != 'function') {
// Needs to be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, "assign", {
value: function assign(target, varArgs) { // Function length is 2
'use strict';
if (target == null) { // TypeError when undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource != null) { // Skip over if undefined or null
for (var key in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, key)) {
to[key] = nextSource[key];
}
}
}
}
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 = decodeURIComponent(pair)[0];
const value = decodeURIComponent(pair)[1];
return Object.assign({}, obj, { [key]: value });
}, {});
return urlObject[pName];
};