JSFiddle - React, Tailwind, and code Playground
by Patrick Gordon
JavaScript
const queryObject = {
not_that: "somethingElse"
};
const keysToMatch = ["utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign", "not_that"];
const queryObjectKeys = Object.keys(queryObject);
if (queryObjectKeys.length === 0) {
return null;
}
const matchUsing = keysToMatch && keysToMatch.length > 0 ? keysToMatch : queryObjectKeys;
const result = matchUsing
.filter(key => typeof queryObject[key] !== "undefined")
.map(key => `${key}=${queryObject[key]}`)
.join("&");
const encodedResult = encodeURIComponent(result);
console.log(encodedResult);