2012-11-18 41 views
2

我有一個字符串文字數組,我想循環它們,將它們解析爲JSON並將屬性添加到生成的對象。我想將這個結果分配給一個變量。使用Coffeescript中的屬性擴展對象?

而且我希望它看起來非常:)

現在我這樣做:

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 這pullrequest:https://github.com/jashkenas/coffee-script/pull/2177 但pullrequest是開放的,問題是關閉的,所以我認爲這樣做至少沒有運營商?

但是,當編寫代碼時,我不禁想到應該有更好的方法,所以任何提示都會受到歡迎。

+0

我寧願不走這條路:http://stackoverflow.com/questions/10941681/extending-javascript-objects-with-coffeescript?rq=1 – ivarni

回答

4

下面是一些參考: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' 
+0

啊,那是一些方便的助手。 – ivarni

+0

不再:現在它是404 :( – lucas

+0

鏈接仍然可以看到使用Wayback機器:http://web.archive.org/web/20161026011849/http://coffeescript.org/documentation/docs/helpers.html – joaumg