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

你离开我真会死。 提交于 2020-07-15 09:29:28

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/51978072/ecmascript-object-spread-rest-assigning-to-multiple-properties-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!