问题
I have an array of values like:
const arr = [1,2,3];
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
};
回答1:
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);
回答2:
You can assign destructurings not only to variables but also to existing objects:
const arr = [1,2,3], o = {};
({0:o.one, 1:o.two, 2:o.three} = arr);
This works without any additional variables and is less repetitive. However, it also requires two steps, if you are very particular about it.
I'm not sure if this helps, since you mentioned computed properties?!
回答3:
With destructuring, you can either create new variables or assign to existing variables/properties. You can't declare and reassign in the same statement, however.
const arr = [1, 2, 3],
obj = {};
[obj.one, obj.two, obj.three] = arr;
console.log(obj);
// { one: 1, two: 2, three: 3 }
回答4:
This answers a slightly different requirement, but I came here looking for an answer to that need and perhaps this will help others in a similar situation.
Given an array of strings : a = ['one', 'two', 'three'] What is a nice un-nested non-loop way of getting this resulting dictionary: b = { one : 'one', two: 'two', three: 'three' } ?
const b = a.map(a=>({ [a]: a })).reduce((p, n)=>({ ...p, ...n }),{})
回答5:
Using destructuring assignment it is possible to assign to an object from an array
Please try this example:
const numbers = {};
[numbers.one, numbers.two, numbers.three] = [1, 2, 3]
console.log(numbers)
The credit to the boys of http://javascript.info/ where I found a similar example. This example is located at http://javascript.info/destructuring-assignment in the Assign to anything at the left-side section
来源:https://stackoverflow.com/questions/38242744/destructure-array-to-object-property-keys