32

我有一个值数组,例如:

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
};
4

9 回答 9

40

您不仅可以将解构值分配给变量,还可以分配给现有对象:

const arr = [1,2,3], o = {};    
({0:o.one, 1:o.two, 2:o.three} = arr);

这无需任何额外的变量即可工作,并且重复性较低。但是,如果您对此非常挑剔,它也需要两个步骤。

于 2016-07-07T11:43:59.950 回答
15

通过解构,您可以创建新变量或分配给现有变量/属性。但是,您不能在同一语句中声明和重新分配。

const arr = [1, 2, 3],
    obj = {};

[obj.one, obj.two, obj.three] = arr;
console.log(obj);
// { one: 1, two: 2, three: 3 }

于 2018-03-21T18:06:26.257 回答
13

我不相信有任何结构化/解构解决方案可以一步完成,不。我想在这个问题中得到类似的东西。旧的:=稻草人提案似乎在新提案列表中没有立足点,所以我认为目前没有太多活动。

恕我直言,这个答案是这里最好的一个(比这个好得多)。两步,但简洁明了。

但如果是两步,你也可以使用一个简单的对象初始化器:

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);

于 2016-07-07T10:11:00.717 回答
6

使用解构赋值可以从数组中赋值给一个对象

请试试这个例子:

const numbers = {};

[numbers.one, numbers.two, numbers.three] = [1, 2, 3]

console.log(numbers)

感谢 http://javascript.info/的男孩们,我在其中找到了一个类似的例子。此示例位于左侧部分的“分配给任何内容”中的http://javascript.info/destructuring-assignment

于 2019-09-12T13:40:02.603 回答
3

这回答了一个稍微不同的要求,但我来这里是为了寻找这个需求的答案,也许这会帮助其他处于类似情况的人。

给定一个字符串数组:a = ['one', 'two', 'three'] 获取此结果字典的一种很好的非嵌套非循​​环方式是什么: b = { one : 'one', two: '二',三:'三' } ?

const b = a.map(a=>({ [a]: a })).reduce((p, n)=>({ ...p, ...n }),{})

于 2017-08-30T04:29:54.843 回答
0

最简单且代码更少的方法之一是解构数组。然后使用这样的常量来更新对象。

const arr = [1, 2, 3];
const [one, two, three] = arr;
const obj = {one, two, three};

console.log(obj);

请注意我是如何通过编写常量 1、2 和 3 的名称来为对象赋值的。当键的名称与属性的名称相同时,您可以这样做。

//Instead of writing it like this
const obj = {one: one, two: two, three: three};
于 2022-01-25T12:00:50.760 回答
0

let distructingNames = ['alu', 'bob', 'alice', 'truce', 'truce', 'truce', 'truce', 'bob'];
let obj={};
distructingNames.forEach((ele,i)=>{
    obj[i]=ele;
})
console.log('obj', obj)

于 2021-02-04T07:36:28.417 回答
0

箭味:

const obj = (([one, two, three]) => ({one, two, three}))(arr)
于 2022-02-25T08:56:39.687 回答
0

您可以使用 lodash 的_.zipObject轻松实现它

const obj = _.zipObject(['one','two','three'], [1, 2, 3]);
console.log(obj); // { one: 1, two: 2, three: 3 }
于 2020-03-12T14:22:45.450 回答