ivarni
ivarni

Reputation: 17878

Extending an object with properties in Coffeescript?

I have an array of string literals and I want to loop over them, parse them as JSON and add a property to the resulting object. I want to assign the result of this to a variable.

And I want it to look pretty :)

Right now I am doing this:

strings = ['{"a": "A", "b": "B"}', '{"c": "C", "d": "D"}']
objects = for string in strings
  obj = JSON.parse string
  obj.e = 'E'
  obj

this gives me an array looking like this:

[{ a: 'A', b: 'B', e:'E' }, { c: 'C', d: 'D', e:'E' }]

Now this works but it looks a bit ugly. I guess what I'd like is something like http://documentcloud.github.com/underscore/#extend (but I don't want to include underscore just for that one method)

I found this issue: https://github.com/jashkenas/coffee-script/issues/880 and this pullrequest: https://github.com/jashkenas/coffee-script/pull/2177 but the pullrequest is open and the issue is closed so I assume there's at least no operator for doing this?

But when writing that code I can't help thinking that there's got to be a better way, so any tips would be welcome.

Upvotes: 2

Views: 6890

Answers (1)

Vyacheslav Voronchuk
Vyacheslav Voronchuk

Reputation: 2463

Here is some reference: http://coffeescript.org/documentation/docs/helpers.html

extend = exports.extend = (object, properties) ->
  for key, val of properties
    object[key] = val
  object

strings = ['{"a": "A", "b": "B"}', '{"c": "C", "d": "D"}']
objects = for string in strings
  extend JSON.parse(string), e: 'E'

Upvotes: 4

Related Questions