41

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
};
4
  • The original purpose of destructuring is to extract values from data stored in (nested) objects/arrays. In your example you create an object. An object literal fits better in this case. Commented Jul 7, 2016 at 10:19
  • Using computed properties would actually cause the inverse of the usual problem. Normally when people want to use a variable as an object literal key, it is seen as a prop. Here you want to define a prop, but it would be seen as a variable (if that syntax was allowed). Or at least it would be ambiguous when there's only one in the brackets. Commented Jul 7, 2016 at 10:24
  • @squint Indeed, that's why I was kind of hoping for a syntax which uses destructuring rather than computed properties, but it doesn't look like that's possible. I guess it makes sense given the longform is really not too much longer, just repetitive. Commented Jul 7, 2016 at 10:27
  • It does look like a compelling syntax, except for the ambiguity of { [foo]: ["bar"] }, which would have to be handled as an unfortunate special case. Commented Jul 7, 2016 at 10:29

10 Answers 10

48

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.

Sign up to request clarification or add additional context in comments.

7 Comments

This is terrifying and amazing at the same time.
In TypeScript, I get an error here. It says: Block scoped variables cannot be redeclared
One line version: const obj = (o = {}, [o.one, o.two, o.three] = arr, o)
@FabianoTaioli: pretty cool, too bad it creates a global o variable
Damn, this JavaScript is amazing :) @FabianoTaioli , this global o var is just for a presentation purposes in this particular case. I think this approach is more for if you have some object, and you want to extend it destructing more items directly in it.
|
23

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 }

2 Comments

This is the best answer IMHO.
This does not work in TypeScript. Any solutions for this?
14

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

4 Comments

There is a almost one-step solution without creating unnecessary variables.
@LUH3417: "almost one-step" = "two-step". :-) But yes, that's another perfectly-valid approach.
it appears you can actually destructure onto object properties, see stackoverflow.com/a/49413688/4273291 or stackoverflow.com/a/57908036/4273291 below
@lohfu - Yes, you can (in fact, I linked to a solution that does in the answer). You can destructure into anything assignable. But it's still two steps.
6

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

1 Comment

Yes. [numbers.one, numbers.two, numbers.three] = [1, 2, 3] works. but, quite literally, so what? It's MORE characters than just typing out numbers.one=1; numbers.two=2; numbers.three=3;! And LOTS more than just numbers={one:1, two:2, three:3}! Hooray! We've managed to that the terse elegant syntax of destructuring and make it LESS efficient than just doing it the (categorically-readable) vanilla way!
3

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 }),{})

1 Comment

You can use Object.assign() with the spread syntax instead of .reduce(): const o = Object.assign(...a.map(val => ({ [val]: val })));
2

Arrow flavor:

const obj = (([one, two, three]) => ({one, two, three}))(arr)

6 Comments

This is the best answer among all others.
Alternative: const obj = (one, two, three) => ({one, two, three})(...arr) 😬
@FrankN I think additional brackets needed: const obj = ((one, two, three) => ({one, two, three}))(...arr)
just verified, yes you're right!
@shtse8 WHY!? WHY is it the best answer!? obj = (([param1, param2, param3, param4, param5]) => ({param1, param2, param3, param4, param5}))(arr) requires MORE CODE than just doing it the old annoying way: obj = {param1: arr[1], param2: arr[2], param3: arr[3], param4: arr[4], param5: arr[5]}! Almost 25% more (102 characters vs 86)! Why is this BETTER!? If you still have to type every key out, TWICE, in this case, why is that faster!? Destructuring assignment is to SPEED the workflow. That is the tradeoff to the loss in readability. This makes it slower, longer to type AND harder to read!
|
0

You can achieve it pretty easily using lodash's _.zipObject

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

Comments

0

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

Comments

0

One of the easiest and less code way is to destructure the array. Then use such constants to update the object.

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

console.log(obj);

Notice how I assigned values to the object by such writing the names of the constants one, two, and three. You can do so when the name of the key is the same of the property.

//Instead of writing it like this
const obj = {one: one, two: two, three: three};

Comments

0

I might be late but, since I have an insight of it, I did love to share. You're fine with how your arrays and objects do look. If you were to destruct an object or array, you do it separately because, in your example, it looks like you're trying to destruct the array. The mistake was you don't have to use {[]} unless you're dealing with an array of objects and you're extracting values from the array, you know. So, you simply use:

const arr = [1, 2, 3];
//Destructuring  
const [ firstElement, secondElement, thirdElement ] = arr; 
console.log(firstElement, secondElement, thirdElement) 

This logs out those array elements.

You can as well use the ...rest operator for combination of other elements at the ending.

1 Comment

You haven't created an object as requested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.