Transforming Arrays of Object in CoffeeScript
I have been doing a lot of data transformation work in CoffeeScript and its features like destructuring assignments is really useful for this. One of the things I needed to do a lot of is given an array of objects, produce an equivalent array of objects having the same data, more or less, but in a different structure.
Originally, to accomplish this, I was following the comprehension example on the CoffeeScript site. With this approach, my code would look something like this:
input = [ value: 1 name: 'a' , value: 2 name: 'b' ] convert = (objectIn) -> id: objectIn.name value: "#{objectIn.value}" output = (convert(obj) for obj in input) |
This simple example takes an array of input objects and from them produces an equivalent array of output objects where the input “name” property becomes the “id” property in the output and the “value” property is transformed from a number to its string equivalent.
The annoying thing about this approach is the need to define conversion functions for each conversion. I was thinking, boy, wouldn’t it be nice if I could just use a regular for loop where I can put a whole block of transformation code into its body and assign the for loop “results” to the output? But for loops of course don’t return results.
Or do they? This is CoffeeScript after all and “everything is an expression.” Moreover, CoffeeScript is very good at just working the way you want it to (except when you forget the fat arrows of course).
So I tried the following:
input = [ value: 1 name: 'a' , value: 2 name: 'b' ] output = for obj in input id: objectIn.name value: "#{objectIn.value}" |
And it works. Now why isn’t this documented anywhere?