将数组析构到对象属性键 [英] Destructure array to object property keys
问题描述
我有一系列值,如:
const arr = [1,2,3];
有什么方法可以使用解构来创建以下输出?如果没有,我在ES6(或更高版本)中最简单的方法是什么?
Is there any way I can use destructuring to create the following output? If not, what is the easiest way I can do this in ES6 (or later)?
const obj = {
one: 1,
two: 2,
three: 3
};
我试过这个,但我猜它不起作用,因为这是计算键的语法:
I tried this, but I guess it doesn't work as this is the syntax for computed keys:
const arr = [1,2,3];
const obj = {
[one, two, three] = arr
};
推荐答案
我不相信有任何结构/解构解决方案一步到位,没有。我想在这个问题中找到类似的 。旧的 :=
strawman提案似乎没有新的提案清单,所以我不知道我认为现在有很多活动。
I don't believe there's any structuring/destructuring solution to doing that in a single step, no. I wanted something similar in this question. The old :=
strawman proposal doesn't seem to have legs in the new proposal list, so I don't think there's much activity around this right now.
这个答案显示了一个非常简洁的两步版本。
This answer shows a very neat two-step version.
但如果它是两个步骤,你也可以使用一个简单的对象初始值设定项:
But if it's two steps, you may as well use a simple object initializer:
const arr = [1,2,3];
const obj = {
one: arr[0],
two: arr[1],
three: arr[2]
};
console.log(obj);
这篇关于将数组析构到对象属性键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!