[英]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.