Search code examples
javascriptecmascript-6ecmascript-2016

Is there a shorthand for this in ES6/ES7?


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.


Solution

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