mansim
mansim

Reputation: 727

Coffeescript loop simplifying

Sended data is Ruby format:

mob = {id: 1, xpos:100, ypos:150, xposDest:150, yposDest:100, attacked:0}
WebsocketRails[:channel_name].trigger(:event_name, mob)

How could i make this loop simpler? (it's coffeescript)

  get_all_mobs: (mob) ->  // getting "mob" with Websockets
    mob_list[mob.id].id = mob.id
    mob_list[mob.id].xpos = mob.xpos if mob.xpos?
    mob_list[mob.id].ypos = mob.ypos if mob.ypos?
    mob_list[mob.id].xposDest = mob.xposDest if mob.xposDest?
    mob_list[mob.id].yposDest = mob.yposDest if mob.yposDest?
    mob_list[mob.id].health = mob.health if mob.health?
    mob_list[mob.id].level = mob.level if mob.level?
    mob_list[mob.id].max_health = mob.max_health if mob.max_health?
    mob_list[mob.id].attacked = mob.attacked if mob.attacked?
    mob_list[mob.id].steps = mob.steps if mob.steps?

Was tryed something like this, but its wrong:

get_all_mobs: (mob) ->  // getting "mob" with Websockets
  for attribute in mob
    mob_list[mob.id].attribute = mob.attribute

Upvotes: 1

Views: 62

Answers (1)

hhelwich
hhelwich

Reputation: 200

This should do:

get_all_mobs: (mob) ->  // getting "mob" with Websockets
  for own key, value of mob
    mob_list[mob.id][key] = value if value?

Upvotes: 4

Related Questions