Map.prototype.addEntries(iterable)

Both Java and Python (and others, surely) have a method on maps to add entries (putAll and update).

Map permits an iterable of entries to the constructor, but has no way to simply add an iterable of entries to an existing map. The current typical code is:

mapA.forEach((val, key) => {mapB.set(key, val)});

or

for (const [key, val] of mapA) {
  mapB.set(key, val);
}

Rather, I'd expect to be able to do the following, as I would in Java or Python:

mapA.addEntries(<iterable>)

where <iterable> is another map, the result of Object.prototype.entries(), or anything else that gives 2-value tuples of key-value pairs.

The best method name is up for debate, but contenders would be addEntries, extend, addAll.

3 Likes

My friend Brad made a good point -- such a method would likely allow a performance improvement over the current iterate-and-set solution (in addition to being more concise and understandable).

I’ve wanted this many times. Seems like it would be an uncontroversial addition to me.

I’d expect a corresponding update to Set. There is an active Set prototype methods proposal, but I don’t think there’d be overlap, because Set.prototype.union is for creating a new Set, rather than for adding items to the receiver set.

You may want to suggest this in this proposal.

@claudiameadows thank you, that looks related.

merge() there seems similar, but I'm a bit unclear on the specific semantics (it's not extensively documented). I will read that doc over.

found https://tc39.es/proposal-collection-methods/#Map.prototype.merge

Looks that's like what we want, though merge() takes variable arguments.

1 Like