Search code examples
javascriptobjectecmascript-nextecmascript-2017

ECMAScript object spread/rest - assigning to multiple properties at once


The new object rest/spread syntax has some surprisingly nice applications, like omitting a field from an object.

Is there a (proposed) way to also assign to several properties of an object, the values from variables with the same names? In other words, a shorter way to say:

o.foo = foo;
o.bar = bar;
o.baz = baz;

Note: Without losing the existing properties of o, only adding to them.


Solution

  • Use Object.assign:

    const o = { initial: 'initial' };
    const foo = 'foo';
    const bar = 'bar';
    const baz = 'baz';
    Object.assign(o, { foo, bar, baz });
    console.log(o);

    Note that both shorthand property names and Object.assign were introduced in ES6 - it's not something that requires an extremely up-to-date browser/environment.

    Something similar that reassigns the reference to the object would be to initialize another object by spreading o and list foo, bar, baz:

    let o = { initial: 'initial' };
    const foo = 'foo';
    const bar = 'bar';
    const baz = 'baz';
    
    o = { ...o, foo, bar, baz };
    console.log(o);