Loourr
Loourr

Reputation: 5125

dynamically adding members to coffee-script object

So currently I have an object which looks like this

module.exports = class Book extends events.EventEmitter

    constructor: ->

        @books = 
            a: new small_book('aaa')
            b: new small_book('bbb')
            c: new small_book('ccc')
            d: new small_book('ddd')

    update: (pair, callback) ->
        @books[pair].update_book()
        @emit 'update'

However, What I would like to be doing is this,

 pairs = 
     a: 'aaa'
     b: 'bbb'
     c: 'ccc'
     d: 'ddd'

 module.exports = class Book extends events.EventEmitter

     constructor: ->       
        for each pair in pairs 
            @books[pair] = new small_book(pairs[pair])

or basically just going through my list and adding exactly as many pairs are in the list. How can I do this?

Upvotes: 0

Views: 191

Answers (1)

mu is too short
mu is too short

Reputation: 434665

From the fine manual:

Comprehensions can also be used to iterate over the keys and values in an object. Use of to signal comprehension over the properties of an object instead of the values in an array.

yearsOld = max: 10, ida: 9, tim: 11

ages = for child, age of yearsOld
  "#{child} is #{age}"

So if you want loop over an object, do it like this:

constructor: ->
    @books = { }       
    for k, v of pairs 
        @books[k] = new small_book(v)

Demo: http://jsfiddle.net/ambiguous/GnVXa/

Upvotes: 1

Related Questions