解构任务构建一个新对象 - 是可能吗? [英] Destructuring assignment to costruct a new object - Is it possible?
问题描述
可以使用解构赋值语法来将数据对象提取到另一个对象,而不是变量吗?
Is it possible to use destructuring assignment syntax to make it possible to extract data objects into another object instead distinct variables?
生成不同变量的示例(foo,bar ):
Example which produce distinct variables (foo, bar):
var {p: foo, q: bar} = {p: 42, q: true};
console.log(foo); // 42
console.log(bar); // true
我需要替代创建一个新对象其中包含以下属性:
I would need in stead to create a new object which contains the following properties as:
var n = {
foo: 42,
bar: true
}
推荐答案
这是不可能的。术语破坏意味着对象被转换为变量。
It is not possible. The term destructuring implies that object is destructured to variables.
用临时变量不污染范围的方法是使用IIFE进行解构:
A way to not pollute the scope with temporary variables is to use IIFE for destructuring:
obj = (({ foo = 'foo', bar = 'bar' }) => ({ foo, bar }))(obj);
这将分配默认值,只会从对象中选择有效的键。
This will assign default values and will pick only valid keys from the object.
如果不需要拣选,用本机JS功能执行此操作的最简单的方法是 Object.assign
:
If picking is not necessary, the cleanest recipe to do this with native JS features is Object.assign
:
obj = Object.assign({ foo: 'foo', bar: 'bar' }, obj);
这篇关于解构任务构建一个新对象 - 是可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!