Hinesh Patel
Hinesh Patel

Reputation: 1251

Extract URL Query String ES6

What is the correct way to extract a query string in ES6?

I have written this function:

getUrlParams(queryString) {
    const hashes = queryString.slice(queryString.indexOf('?') + 1).split('&');
    const params = {};
    hashes.map((hash) => {
      const [key, val] = hash.split('=');
      params[key] = decodeURIComponent(val);
    });

    return params;
  }

However ESLint compains that it expected this to be used by class method and it expected a return value in the arrow function.

Upvotes: 1

Views: 2409

Answers (2)

Estus Flask
Estus Flask

Reputation: 222503

It complains because map is supposed to map function argument to its return value, not just iterate.

It can be changed to simple loop:

const params = {};
for (const hash of hashes) {
  const [key, val] = hash.split('=');
  params[key] = decodeURIComponent(val);
}

Or an array can be reduced to an object:

return hashes.reduce((params, hash) => {
  const [key, val] = hash.split('=');
  params[key] = decodeURIComponent(val);
}, {});

Upvotes: 0

raina77ow
raina77ow

Reputation: 106375

You don't need to use .map when you don't care about the return value; use .forEach instead:

hashes.forEach(hash => {
  const [key, val] = hash.split('=');
  params[key] = decodeURIComponent(val);
});

See, .map function is usually expected to return a new collection (where each item represents some relation to the item of the original collection).

In fact, you can simplify this with .reduce():

const params = hashes.reduce((params, hash) => {
  const [key, val] = hash.split('=');
  params[key] = decodeURIComponent(val);
  return params;
}, {});
return params;

Upvotes: 2

Related Questions