Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
280 views
Welcome To Ask or Share your Answers For Others

1 Answer

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?!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...