0
w = {c: true}
w =
  a: 4
  b: true
console.log w

I expect the result w to be {a: 4, b: true, c: true}, but I get {a: 4, b: true}. How can I do multiple assignments to object properties without loosing already set properties?

Tomasz Zieliński
  • 16,136
  • 7
  • 59
  • 83
ronnydw
  • 923
  • 16
  • 24
  • 1
    The answers to [this question](http://stackoverflow.com/q/929776/306084) might prove useful, as what you're doing is merging properties in to the initial object. – pjmorse Sep 17 '14 at 14:35

3 Answers3

1

CoffeeScript: assigning multiple properties to an initialised object has been the best answer so far.

But if you only want to add a few properties to an object you can just do:

w = {c: true}
w.a = 4
w['b'] = true  # alternative notation

Also, this question is more about JavaScript than CoffeeScript.

Tomasz Zieliński
  • 16,136
  • 7
  • 59
  • 83
  • That's obviuous I know ... but not very pretty, I am looking for a short notation, in real life w is an object with a long name and I have many properties to add. – ronnydw Sep 17 '14 at 14:54
0

I don't think it can be done directly. I believe, you need to iterate:

w = {c: true}
temp =
  a: 4
  b: true
w[k] = v for k,v of temp
console.log w
Jakub Fedyczak
  • 2,174
  • 1
  • 13
  • 15
0
w = {c: true}
w[i] = v for i,v of {
  a: 4
  b: true
}
console.log w
YuS
  • 2,025
  • 1
  • 15
  • 24