From Vanilla Javascript to ES6 Spread Operator

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

Answer №1

If you want to merge objects in JavaScript, consider using the Object.assign() method:

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

Check out this live example:

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

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

By the way, the { ...obj } syntax is known as "Object Rest/Spread Properties" and is a feature introduced in ECMAScript 2018, not in ECMAScript 6.

Answer №2

If you are looking for the syntax of ES5, here is a custom solution for Object.assing() (source: MDN)

   

// Assigning null to Object.assign to demonstrate the working polyfill
Object.assign = null;

// Start of polyfill

if (typeof Object.assign != 'function') {
  // Set characteristics to writable:true, enumerable:false, and configurable:true
  Object.defineProperty(Object, "assign", {
    value: function assign(target, varArgs) { // Function length set to 2
      'use strict';
      if (target == null) { // Throw TypeError on 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) {
            // Handle cases where hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
}

// End of polyfill


   // Example usage 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting issue with Next.JS Redux dispatch functionality inside getStaticProps() not functioning as

I have recently started working with Next.JS and decided to integrate Redux into my Next.JS application. I'm facing an issue where my page is supposed to display a list of posts fetched from an API. Everything works fine when I use useEffect() to disp ...

Unable to find the element using the text "selenium webdriver"

Currently, I am working with Selenium WebDriver using Java. Log.info("Clicking on To weekrange dropdown"); JavascriptExecutor executor25 = (JavascriptExecutor)driver; executor25.executeScript("document.getElementById('toWeekYear).style.display=' ...

Swapping out components or features within AngularJS

Is it possible to make my dependencies interchangeable in AngularJS? For example, if I have a service named myService stored within the module myDependency, how can I switch out myDependency with a new service without disrupting the main application? Shou ...

PHP Calculator with Dynamic Calculations

I need to create an order form that updates the tax and total automatically once a quantity is entered into the text box. Should I use PHP or JavaScript for this functionality? Let's assume, for instance, that the tax rate is 0.3% My requirements: ...

Alert: Ajax encountered an issue with the auto-refreshing field

When running a script I created for a self-updating field, I encountered the following error message: UpdateField.html:37 Uncaught ReferenceError: fieldname is not defined at HTMLInputElement.onchange (UpdateField.html:37) Script: <!DOCTYPE ht ...

Update the input value following a successful action

How can I update the value of an input field after a successful ajax call? I have tried the following approach but it doesn't seem to be working. The result from the alert is 80000 Here is the HTML input code: <input class="form-control" type=" ...

Endless loop in XMLHttpRequest()

I am trying to use Ajax in the code snippet below to continuously retrieve a PHP query result until it reaches "6". The code seems to be functioning correctly, but once the result is "6", the script does not stop running. Instead, my CPU fan starts making ...

Adding a trailing slash to the URL in an Express server causes it to be appended

I've encountered a strange issue with my express server. Whenever I try to use a specific URL route with the word 'bind,' an extra '/' is automatically added to it. This behavior isn't happening with other URLs that I've ...

Sending a PDF document to a function that specifically calls for a file location or URL

Currently, I am developing a web application for an online library where I need to extract metadata from PDF files that are uploaded. To achieve this, I am utilizing the nodejs libraries pdf.js-extract and multer-gridfs-storage for file uploads. However, I ...

Advantages of placing script src tags at the top of the body versus placing them at the bottom of the body

I've heard that it's best to place the script tags right before the closing body tag. However, when I follow this advice, my angularJS expressions don't seem to compute correctly for some reason. When I place the script tags in that location ...

Tips on creating type definitions for CSS modules in Parcel?

As someone who is brand new to Parcel, I have a question that may seem naive. In my project, I am using typescript, react, less, and parcel. I am encountering an error with typescript stating 'Cannot find module 'xxx' or its corresponding t ...

Eliminate an element from a jsonb array based on its value

After successfully removing a value from an array for a single record, I now face the challenge of doing it for multiple records. My current obstacle lies in how I am utilizing the subquery, which is meant to return only a single element. It's possibl ...

Creating code that is easily testable for a unique test scenario

My function, readFile(path, callback), is asynchronous. The first time it reads a file, it retrieves the content from the file system and saves it in memory. For subsequent reads of the same file, the function simply returns the cached content from memor ...

Establishing foreignObject coordinates in Angular

Struggling with setting the position (x, y) for foreignObject in Angular. I have attempted the following: <foreignObject width="65" height="50" x="{{position?.x}}" y="{{position?.y}}"> <div class="c ...

What is the accurate user agent for Windows Phone?

Can someone explain why PHP and JavaScript produce different user agents? Which one is considered the accurate user agent? PHP User Agent Output: <?php print_r($_SERVER['HTTP_USER_AGENT']); ?> User Agent: Mozilla/5.0 (Mobile; Windows Ph ...

The velocity of jQuery selectors

Which is more efficient: using only the ID as a selector or adding additional identifiers? For instance $('#element') vs $('#container #element') or getting even more detailed: $('body div#container div#element') ? ...

Revamp your AngularJS controller for a fresh new look

How can a controller be refreshed in Angular? Take into account the scenario below: <div ng-controller="MsgCtrl" ng-repeat="m in messages">{{m}}<br></div> <script> var ws = new WebSocket(something, something); function MsgCtrl($sco ...

If the value of the "Global Region" field in the PDF form is not empty, then execute the following JavaScript code:

I need to restrict access to a PDF form when the "Global Region" field is filled out. Testing this code can be time-consuming, so I want to confirm that the syntax to check for a NOT NULL value in the Global Region Field is correct. if(this.getField("Gl ...

What is the reason for XMLHttpRequest.status being equal to 0 in all browsers except for Internet Explorer?

I am encountering a frustrating issue... After developing a standalone RESTful.NET webservice using C#, I noticed that when I make a XMLHttpRequest to fetch JSON data, all browsers, except for IE, fail to retrieve the data. The problem lies in the status ...