简体   繁体   English

ECMAScript 对象传播/休息 - 一次分配给多个属性

[英]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 .新的 object rest/spread 语法有一些非常好的应用,比如从 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.注意:在不丢失o现有属性的情况下,只添加它们。

Use Object.assign :使用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.请注意,速记属性名称和Object.assign都是在 ES6 中引入的——它不需要非常最新的浏览器/环境。

Something similar that reassigns the reference to the object would be to initialize another object by spreading o and list foo, bar, baz :将引用重新分配给对象的类似方法是通过传播o列表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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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