1

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.

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that worked but I am still getting an error stating that getUrlParams(queryString) expected this. I am calling this method inside my getSearchResults() as const { terms, category } = this.getUrlParams(this.props.location.search);
You're welcome. As for new error, I'd rather make a new question for this - it seems to be more about the structure of your component then about algorithms used.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.