Is there no ubiquitous/standard Javascript or Coffeescript function that Transforms the values of an object/map/hash?
jQuery has $.map but it produces Arrays only.
Underscore has _.map but it also produces Arrays only.
To be clear, a function like this one is what I’m looking for. (This example is written in Coffeescript not Javascript.)
# Transforms the values in a map. (Doesn't modify `obj` — returns a new map.)
# Example usage:
# mapObjVals({ a: 'aa', b: 'bb'}, (key, value) -> value + '_!')
# --> { a: 'aa_!', b: 'bb_!' }
mapObjVals = (obj, f) ->
obj2 = {}
for k, v of obj
obj2[k] = f k, v
obj2
If you want to map an object to an object, you need to use a
fold(traditional functional terminology) orreduce(common modern name, used by underscore), which builds a new value from a collection:The function passed as the second argument is called once per key/value pair. It is passed in the object being built as its first argument, followed by the current value, followed by the associated key. It is up to the function to modify the object and return its new value.
The third argument to
_.reduceis the initial value of the new object, to be passed in with the first key/value pair; in this case it’s an empty object/map/hash{}.Reduce/fold/inject is commonly used for summing values. Basically, any time you want to construct a new single value from a collection.
mapis really just a special case ofreducewhere the allegedly-reduced value is really another collection of the same size as the original.For CoffeeScript, AFAIK, list comprehensions always return lists, even when iterating over an object. So you might want to look into the CoffeeScript version of Underscore.