解构赋值以构建新对象 - 有可能吗?

Rad*_*dex 7 javascript ecmascript-6 babeljs

是否可以使用解构赋值语法来将数据对象提取到另一个对象而不是不同的变量中?

产生不同变量的示例 (foo, bar):

var {p: foo, q: bar} = {p: 42, q: true};
 
console.log(foo); // 42
console.log(bar); // true  
Run Code Online (Sandbox Code Playgroud)

相反,我需要创建一个包含以下属性的新对象:

var n = {
foo: 42,
bar: true
}
Run Code Online (Sandbox Code Playgroud)

Est*_*ask 12

It is not possible. The term destructuring implies that object is destructured to variables.

A way to not pollute the scope with temporary variables is to use IIFE for destructuring:

obj = (({ foo = 'foo', bar = 'bar' }) => ({ foo, bar }))(obj);
Run Code Online (Sandbox Code Playgroud)

This will assign default values and will pick only valid keys from the object.

If picking is not necessary, the cleanest recipe to do this with native JS features is ES6 Object.assign:

obj = Object.assign({ foo: 'foo', bar: 'bar' }, obj);
Run Code Online (Sandbox Code Playgroud)

Or ES2018 spread:

obj = { foo: 'foo', bar: 'bar', ...obj};
Run Code Online (Sandbox Code Playgroud)