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?

1
  • 1
    The answers to this question might prove useful, as what you're doing is merging properties in to the initial object. Commented Sep 17, 2014 at 14:35

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

3 Comments

hmm... this does the assigment of each property twice
True, but solution from @Yuri does it same way - look at the transpiled code.
Most efficient way seems to be from @Tomasz Zieliński - not very pretty though.
0
w = {c: true}
w[i] = v for i,v of {
  a: 4
  b: true
}
console.log w

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.