data_query-to-json.js

/**
 * @module queryToJson
 * @description Uses JSON.parse() to transform a string in query format (i.e. query1=val&query2=val2 ) into an object.
 *
 * @since 1.0.0
 *
 * @param {string} params The query style string to be parsed. If ommitted, the query portion of the current URL is used.
 *
 * @return {object} Returns an object based on the specified params or the current URL's query portion.
 *
 * @example
 * import { queryToJson } from "@gravityforms/utils";
 *
 * function Example() {
 *   const params = 'query1=val1&query2=val2';
 * 	 const obj = queryToJson( params );
 * }
 *
 */
const queryToJson = ( params = '' ) => {
	const query = params.length ? params : window.location.search.slice( 1 );
	const pairs = query.length ? query.split( '&' ) : [];
	const result = {};
	let pairArray = [];

	pairs.forEach( ( pair ) => {
		pairArray = pair.split( '=' );
		result[ pairArray[ 0 ] ] = decodeURIComponent( pairArray[ 1 ] || '' );
	} );

	return JSON.parse( JSON.stringify( result ) );
};

export default queryToJson;