【问题标题】:Extending an object with properties in Coffeescript?在 Coffeescript 中扩展具有属性的对象?
【发布时间】:2012-11-18 20:34:59
【问题描述】:

我有一个字符串字面量数组,我想遍历它们,将它们解析为 JSON 并向结果对象添加一个属性。我想将这个结果分配给一个变量。

我希望它看起来很漂亮:)

现在我正在这样做:

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

这给了我一个如下所示的数组:

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

现在这可行,但看起来有点难看。我想我想要的是 http://documentcloud.github.com/underscore/#extend 之类的东西(但我不想只为那个方法添加下划线)

我发现了这个问题:https://github.com/jashkenas/coffee-script/issues/880 这个拉取请求:https://github.com/jashkenas/coffee-script/pull/2177 但是 pullrequest 是打开的并且问题已关闭,所以我认为至少没有操作员可以这样做?

但是在编写该代码时,我不禁想到必须有更好的方法,因此欢迎提供任何提示。

【问题讨论】:

标签: coffeescript


【解决方案1】:

这里有一些参考: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'

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 2012-12-06
  • 1970-01-01
相关资源
最近更新 更多