url icon indicating copy to clipboard operation
url copied to clipboard

URLSearchParams.appendAll(iterable)

Open ethanresnick opened this issue 4 years ago • 8 comments

This is a feature request for the functionality mentioned in the title. (Hopefully this is the right place for such requests.) Basically, it'd be really nice to be able to merge a bunch of items into a URL's existing query string, without having to do an explicit loop and call append on each iteration, hence something like:

const newParams = { a: true, b: false };
const url = new URL(inputUrl);
url.serachParams.appendAll(Object.entries(newParams));

ethanresnick avatar Dec 27 '19 13:12 ethanresnick

Heya, welcome! https://whatwg.org/faq#adding-new-features might be worth reading.

I'm wondering, is this a popular pattern in libraries / existing code today that makes it worth putting in the standard library? Is this often requested on Stack Overflow or equivalent forums?

annevk avatar Jan 02 '20 07:01 annevk

Anecdotal, @annevk, but personally I try to use the non-existent appendAll a few times a year.

(Certainly not a big nuisance that it’s absent — just surprising, I think, if one has been trained to expect symmetry from APIs like this.)

bathos avatar Feb 15 '20 12:02 bathos

Symmetry with getAll()? Wouldn't that require a different signature from OP?

annevk avatar Feb 16 '20 16:02 annevk

Yes — I missed that in the OP, the method I keep imagining exists is appendAll(key, values), though I can see the utility of an entries-consuming method.

bathos avatar Feb 16 '20 16:02 bathos

Angular has this implemented in their HttpParams class and serves the same purpose as described in this issue. https://angular.io/api/common/http/HttpParams#appendAll

damncodingdam avatar Sep 18 '21 10:09 damncodingdam

It would be nice if TC39 established some precedent here with their Map API, although I realize it's not quite the same due to duplicate keys not presenting an issue here.

(@bathos for your use case it might make sense to turn value into a rest parameter on append() and set(). Probably best as a separate issue.)

annevk avatar Mar 06 '23 01:03 annevk

Anecdotal, @annevk, but personally I try to use the non-existent appendAll a few times a year.

(Certainly not a big nuisance that it’s absent — just surprising, I think, if one has been trained to expect symmetry from APIs like this.)

GitHub Copilot seems to try that too:

image

TechAurelian2 avatar Mar 14 '23 12:03 TechAurelian2

@annevk great idea — that’s a neater solution all around for the cases I described. new issue opened: #762

bathos avatar Mar 14 '23 12:03 bathos