如何在ES6中将结构化为动态命名的变量? [英] How to destructure into dynamically named variables in ES6?
问题描述
假设我有以下对象:
const user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
};
我只想要 id
和 fullName
。
我将执行以下操作:
const { id, fullName } = user
Easy-peasy ,对吗?
Easy-peasy, right?
现在让我们假设我想根据另一个名为字段
的变量的值进行解构。
Now let's suppose that I want to do the destructuring based on the value of another variable called fields
.
const fields = [ 'id', 'fullName' ]
现在我的问题是:如何根据一系列密钥进行解构?
我无耻地尝试以下方法但没有成功:
I shamelessly tried the following without success:
让{[{... fields}]} = user
和让{[... fields]} =用户
。有没有办法可以做到这一点?
let {[{...fields}]} = user
and let {[...fields]} = user
. Is there any way that this could be done?
谢谢
推荐答案
使用动态密钥进行结构化并非不可能。为了防止创建动态变量的问题(如Ginden所提到的),您需要提供别名。
It's not impossible to destructure with a dynamic key. To prevent the problem of creating dynamic variables (as Ginden mentioned) you need to provide aliases.
const user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
};
const fields = [ 'id', 'fullName' ];
const object = {};
const {[fields[0]]: id, [fields[1]]: fullName} = user;
console.log(id); // 42
console.log(fullName); // { firstName: "John", lastName: "Doe" }
解决问题必须为动态值定义静态别名,您可以分配给对象的动态属性。在这个简单的例子中,这与恢复整个解构相同,但是:)
To get around the problem of having to define static aliases for dynamic values, you can assign to an object's dynamic properties. In this simple example, this is the same as reverting the whole destructuring, though :)
const user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
};
const fields = [ 'id', 'fullName' ];
const object = {};
({[fields[0]]: object[fields[0]], [fields[1]]: object[fields[1]]} = user);
console.log(object.id); // 42
console.log(object.fullName); // { firstName: "John", lastName: "Doe" }
来源:
这篇关于如何在ES6中将结构化为动态命名的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!