query-string icon indicating copy to clipboard operation
query-string copied to clipboard

How to skip duplicate key in query string

Open kingpinzs opened this issue 3 years ago • 5 comments

Could not find a from to post this question in so posting it here. How can I skip a key that has already been parsed/added? Is there an option I can add to queryString.parse(location.search) to ignore duplicates?

kingpinzs avatar Nov 09 '20 21:11 kingpinzs

It's not immediately clear to me exactly what you are asking. An example might go a long way.

sindresorhus avatar Nov 20 '20 12:11 sindresorhus

For example ?utm_source=google&utm_medium=ppc&utm_campaign=brand&utm_source=google As of now utm_source becomes an array but I would prefer to ignore the second utm_source

kingpinzs avatar Nov 20 '20 15:11 kingpinzs

I think https://github.com/sindresorhus/query-string/issues/210 would solve this, as you could define that utc_source is a string and it would only use the first value.

sindresorhus avatar Nov 20 '20 15:11 sindresorhus

I'd also really like to see this for making TypeScript code more succinct. Maybe something like arrayFormat: 'ignore'?

Current code looks like:

function doThingWithParam(param: string) {
  // ...
}

// param type is string | string[] | null
let { param } = qs.parse(search);
if (Array.isArray(param)) {
  param = param[0];
}
doThingWithParam(param);

ideally it'd be something like

// param type is string | null
let { param } = qs.parse(search, { arrayFormat: 'ignore' });
doThingWithParam(param);

wbobeirne avatar Nov 18 '21 22:11 wbobeirne

+1 on this

nicovigil1 avatar Oct 06 '22 19:10 nicovigil1