Place Query Search Parameters Into a Hash

Last modified: 
Monday, May 7th, 2018
Topics: 
JavascriptES6

An ES6-friendly means to place all query string arguments into a hash with key mapped to value. (URLSearchParams doesn't seem to be especially good for this.) Note, the use of spread operator here will reduce any duplicate keys to the final item iterated through.

export const locationSearchToHash = paramsString => {
  return paramsString.slice(1).split('&').reduce((acc, current) => {
    let pair = current.split('=');
    if (pair.length === 2) {
      let ins = {};
      ins[pair[0]] = pair[1];
      return { ...acc, ...ins };
    } else {
      return acc;
    }
  }, {});
};


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.