Javascript到Coffeescript推入foreach

Javascript到Coffeescript推入foreach,javascript,loops,collections,coffeescript,Javascript,Loops,Collections,Coffeescript,我想知道如何改变这个 lastVoted ().forEach (function (voted) { voted.decision.forEach (function (decision) { var d = Decisions.findOne (decision.id); lastDecisionsVoted.push ({ id: decision.id, title: d.title, choice: (

我想知道如何改变这个

  lastVoted ().forEach (function (voted) {
    voted.decision.forEach (function (decision) {
      var d = Decisions.findOne (decision.id);
      lastDecisionsVoted.push ({
        id: decision.id,
        title: d.title,
        choice: (decision.choice == 'red' ? d.red : d.blue),
        choiceclass: (decision.choice == 'red' ? 'text-danger' : 'text-info'),
        nochoice: (decision.choice == 'red' ? d.blue : d.red),
        nochoiceclass: (decision.choice == 'red' ? 'text-info' : 'text-danger')
      });
    });
  });

变成咖啡脚本。。。我已经查看了文档和这里的一些答案,但我找不到我的案例的确切答案,只有一个简单的foreach循环…

发现它比我想象的要简单,所以如果有人面临同样的问题,这里就是

lastVoted().forEach (voted) ->
    voted.decision.forEach (decision) ->
      d = Decisions.findOne(decision.id)
      lastDecisionsVoted.push
        id: decision.id
        title: d.title
        choice: ((if decision.choice is "red" then d.red else d.blue))
        choiceclass: ((if decision.choice is "red" then "text-danger" else "text-info"))
        nochoice: ((if decision.choice is "red" then d.blue else d.red))
        nochoiceclass: ((if decision.choice is "red" then "text-info" else "text-danger"))

你也可以把它作为一个列表

decide = (voted)->
  getOne = (decision)->
    # method body here
  getOne(decision) for decision in voted.decision

decide(voted) for voted in lastVoted()
或者你可以这样做:

class VoteDecision
  constructor: ({@choice, @id, @title})->
    findItem()

  findItem: ->
    @item = Decisions.findOne(@id)

  toObj: ->
    id: @id
    title: @title
    choice: @choice()
    choiceclass: @choiceClass()
    # etc

  choice: ->
    if @choice == 'red' then @item.red else @item.blue

  choiceClass: ->
    if @choice is "red" then "text-danger" else "text-info"

decide = (voted)->
 lastDecisionsVoted.push(new VoteDecision(decision).to_obj for decision in voted.decision)

decide(voted) for voted in lastVoted()
(我用手做的,但应该接近你需要的)