Reputation: 46489
I thought this might be built-in, but doesn't seem to be. What's the best way to do populate a new class instance from a hash of properties?
Upvotes: 2
Views: 369
Reputation: 18288
It is indeed built in. You can put @ symbols infront of the variables inside the hash:
class Cat
constructor: ({@name, @age}) ->
myCat = new Cat {name:'kitty', age:3}
This is part of "Destructuring Assignment" which you can read about on the coffescript website. It even works with nested objects, arrays and even splats.
Upvotes: 6
Reputation: 37091
You could do something like this:
class Foo
constructor: (params = {}) ->
for key, value of params
this[key] = value
f = new Foo(var1: "foo", var2: "bar")
console.log(f)
Upvotes: 1