mapValues & friends
Transforms every value, every key, or the whole (key, value) entry of a map.
Lecture
The rest of section 9 selects from a map —
pick,
omit,
pickBy,
omitBy — or reads one part of it.
These three transform it. mapValues runs every value
through a callback and leaves the keys alone, mapKeys does
the reverse, and mapEntries takes the whole
(key, value) record and gives back a new one.
That record is the same shape pickBy, omitBy and
fromEntries already use, so
the four compose without any adapting: filter with one, transform with the
other. mapEntries generalises the other two — swapping
e.$1 and e.$2 inverts a map in one call.
mapValues can never lose an entry, because the keys are
untouched. mapKeys and mapEntries can: if the
callback maps two keys onto the same result, the last one
in iteration order wins, exactly as a repeated key in a map literal would.
Insertion order otherwise survives, following the first appearance of each
new key.
There is deliberately no filter or filterWithKey
here. pickBy and omitBy already take the whole
record, so ignoring one half is how you filter by the other — see the
second demo.
Compare evolve, next door: it
transforms the values of named keys and passes the rest through.
mapValues is the case where every value gets the same
treatment.
Demo 1 · Basics
Demo 2 · Collisions, and filtering alongside
Try it yourself
Exercise: turn every score into a letter grade, keeping the names.
evolve — transform the values of named keys only ·
pickBy / omitBy — the key-aware filters, same record shape ·
fromEntries — build a map from records ·
compactObject — drop the null values