Javascript到Coffeescript进入foreach

时间:2014-05-22 12:33:30

标签: 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: (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')
      });
    });
  });

进入coffeescript ......我在这里看了一些文档和一些答案,但我找不到我的案例的确切答案,只有一个简单的foreach循环......

2 个答案:

答案 0 :(得分:0)

发现这比我想象的要简单得多,如果有人面临同样的问题

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"))

答案 1 :(得分:0)

您也可以将其作为列表理解

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()

(我手工完成,但它应该接近你需要的那些)