Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructure array to object property keys

People also ask

Can you Destructure an array?

You can destructure an array more than once in the same code snippet.

Why would you Destructure an array?

Destructuring can make working with an array return value more concise. In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

How do you Destructure an object in es6?

When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.


You can assign destructured values 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 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.

IMHO, this answer is the best one here (much better than this one). Two steps, but concise and simple.

But if it's two steps, you could also use a simple object initializer:

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

Another option is to do it with several temporary arrays but technically only one statement (I am not advocating this, just noting it):

const arr = [1,2,3];
const obj = Object.fromEntries(
    ["one", "two", "three"].map((name, index) =>
        [name, arr[index]]
    )
);
console.log(obj);

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 }

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