2

I'm having a bit of a brainfart. Is there a shorthand for this in ES6/ES7?

res.locals.hello = hello

I've tried a few different combinations but can't get anything to stick.

Anthony
  • 13,434
  • 14
  • 60
  • 80
  • 1
    What kind of shorthand would you be looking for? I can't think of any reasonable way this could be simplified. – Jack Guy Nov 11 '15 at 20:05
  • You may be thinking of `{ hello }` which transpiles to `{ hello: hello }`. This is one of many enhancements made to object literals in ES6. – Sampson Nov 11 '15 at 20:06
  • Well if I wanted to destructure this the other way around, I Could use `let { hello } = res.locals` . I was hoping there was a similar shorthand for going the other direction. – Anthony Nov 11 '15 at 20:08
  • looks pretty short to me. you can make it shorter by minifying it. r.l.h=h – ergonaut Nov 11 '15 at 20:08
  • I hope we don't get questions like this for every possible thing you could do in JavaScript. – Felix Kling Nov 11 '15 at 20:21
  • Not sure what the issue is. I thought there was a solution but surprisingly couldn't find it while tinkering. I posted the question to SO and someone helped me with a solution. Is there something inherently wrong with that in your view? – Anthony Nov 11 '15 at 20:25
  • In more complicated scenarios (i.e. when you want to assign several fields) you may do it with `Object.assing`, e.g. `Object.assing(res.locals, { hello }) `. – Leonid Beschastny Dec 25 '15 at 15:47
  • Thanks for the post Leonid but you've got a little typo, should be `Object.assign(res.locals, { hello })` (haven't tested) – Anthony Dec 25 '15 at 20:31

2 Answers2

4

I don't believe there is a shorter way to arbitrarily attach a new key to an object, and automatically assign a reference with the same name. However, during the construction of your locals object, you can simply provide the handler:

let res = {
    locals: { hello }
};

This is effectively the same as:

let res = {
    locals: {
        hello: hello
    }
};

This enhancement was added in ES6, and is supported by all transpilers to my knowledge.

Sampson
  • 265,109
  • 74
  • 539
  • 565
0

Yes, assuming res already exists, using res.locals = { hello } works just fine.

Anthony
  • 13,434
  • 14
  • 60
  • 80