简体   繁体   中英

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.

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM