我有一个值数组,例如:
const arr = [1,2,3];
有什么方法可以使用解构来创建以下输出吗?如果没有,在 ES6(或更高版本)中执行此操作的最简单方法是什么?
const obj = {
one: 1,
two: 2,
three: 3
};
我尝试过这个,但我想它不起作用,因为这是计算键的语法:
const arr = [1,2,3];
const obj = {
[one, two, three] = arr
};
您不仅可以将解构值分配给变量,还可以分配给现有对象:
const arr = [1,2,3], o = {};
({0:o.one, 1:o.two, 2:o.three} = arr);
这无需任何额外变量即可工作,并且重复性较低。不过,如果你非常讲究的话,它也需要两个步骤。
通过解构,您可以创建新变量或分配给现有变量/属性。但是,您不能在同一语句中声明和重新分配。
const arr = [1, 2, 3],
obj = {};
[obj.one, obj.two, obj.three] = arr;
console.log(obj);
// { one: 1, two: 2, three: 3 }
我不相信有任何结构化/解构解决方案可以一步完成这一点,不。我想要类似的东西在这个问题中。旧的
:=
稻草人提案 似乎在新的 提案列表 中没有立足之地,所以我认为目前围绕此问题没有太多活动。
恕我直言,这个答案是这里最好的答案(比这个好得多)。两步,但简洁明了。
但是如果是两个步骤,您也可以使用一个简单的对象初始值设定项:
const arr = [1,2,3];
const obj = {
one: arr[0],
two: arr[1],
three: arr[2]
};
console.log(obj);
另一种选择是使用多个临时数组来完成此操作,但从技术上讲只有一个声明(我不提倡这一点,只是注意到它):
const arr = [1,2,3];
const obj = Object.fromEntries(
["one", "two", "three"].map((name, index) =>
[name, arr[index]]
)
);
console.log(obj);
使用解构赋值可以从数组中赋值给对象
请尝试这个例子:
const numbers = {};
[numbers.one, numbers.two, numbers.three] = [1, 2, 3]
console.log(numbers)
感谢 http://javascript.info/ 的男孩们,我在那里找到了一个类似的例子。此示例位于“分配给左侧的任何内容”部分中的 http://javascript.info/destructuring-assignment
给定一个字符串数组:a = ['一', '二', '三'] 获取结果字典的一种很好的非嵌套非循环方式是什么: b = { one : 'one', Two: 'two', Three: ' Three' } ?
const b = a.map(a=>({ [a]: a })).reduce((p, n)=>({ ...p, ...n }),{})
const obj = (([one, two, three]) => ({one, two, three}))(arr)
let distructingNames = ['alu', 'bob', 'alice', 'truce', 'truce', 'truce', 'truce', 'bob'];
let obj={};
distructingNames.forEach((ele,i)=>{
obj[i]=ele;
})
console.log('obj', obj)
const arr = [1, 2, 3];
const [one, two, three] = arr;
const obj = {one, two, three};
console.log(obj);
注意我是如何通过写常量一、二和三的名称来给对象赋值的。当键的名称与属性相同时,您可以这样做。
//Instead of writing it like this
const obj = {one: one, two: two, three: three};
const arr = [1,2,3]
const [one,two,three] = [...arr]
const newObj = {one,two,three}
console.log(newObj)