36

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
};
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • 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. –  Jul 07 '16 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. –  Jul 07 '16 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. – CodingIntrigue Jul 07 '16 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. –  Jul 07 '16 at 10:29

9 Answers9

42

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 20
    This is terrifying and amazing at the same time. – Qix - MONICA WAS MISTREATED Aug 09 '17 at 14:52
  • In TypeScript, I get an error here. It says: Block scoped variables cannot be redeclared – Marecky Jan 21 '21 at 10:59
  • @Marecky - It shouldn't, and [doesn't for me](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwTAvDA2gRgDQCZsDMAutjCKjAN4C+8EMAColAJZwA2APJeAKYBcMMAFcAtgCNeCANwwoAdxCCREqbKgALBLwFCxkmdQB80gFAAKSgAZ+IAHR9SmW3YUhSuF5u29aaRAgAlNJAA). You do have to give `o` a type (otherwise, it doesn't have `one`, `two`, or `three` properties). – T.J. Crowder Nov 13 '21 at 10:40
  • Here is a [live demo](https://viebel.github.io/klipse-embed/?src=JTJGJTJGJTIwRWRpdCUyMHRoZSUyMGNvZGUlMkMlMjB0aGUlMjBicm93c2VyJTIwZXZhbHVhdGVzJTIwYXMlMjB5b3UlMjB0eXBlJTIwJTBBJTVCMSUyQyUyMDIlMkMlMjAzJTJDJTIwNCUyQyUyMDUlNUQubWFwKHglMjAlM0QlM0UlMjB4JTIwJTJCJTIwMSklM0I%3D&lang=javascript) – viebel Jan 25 '22 at 12:32
  • One line version: `const obj = (o = {}, [o.one, o.two, o.three] = arr, o)` – Fabiano Taioli Feb 25 '22 at 08:53
17

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 }
adambullmer
  • 952
  • 9
  • 29
13

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);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • There is a almost [one-step solution](http://stackoverflow.com/a/38244614/6445533) without creating unnecessary variables. –  Jul 07 '16 at 11:47
  • 2
    @LUH3417: "almost one-step" = "two-step". :-) But yes, that's another perfectly-valid approach. – T.J. Crowder Jul 07 '16 at 12:02
  • it appears you can actually destructure onto object properties, see https://stackoverflow.com/a/49413688/4273291 or https://stackoverflow.com/a/57908036/4273291 below – lohfu Aug 12 '20 at 14:25
  • @lohfu - Yes, you can (in fact, I linked to [a solution](https://stackoverflow.com/a/38244614/157247) that does in the answer). You can destructure into anything assignable. But it's still two steps. – T.J. Crowder Aug 12 '20 at 14:49
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

Mario
  • 4,784
  • 3
  • 34
  • 50
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 }),{})

corse32
  • 166
  • 5
  • You can use `Object.assign()` with the spread syntax instead of `.reduce()`: `const o = Object.assign(...a.map(val => ({ [val]: val })));` – gilly3 Sep 25 '18 at 18:36
1

Arrow flavor:

const obj = (([one, two, three]) => ({one, two, three}))(arr)
Fabiano Taioli
  • 5,270
  • 1
  • 35
  • 49
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 }
Technotronic
  • 8,424
  • 4
  • 40
  • 53
0

let distructingNames = ['alu', 'bob', 'alice', 'truce', 'truce', 'truce', 'truce', 'bob'];
let obj={};
distructingNames.forEach((ele,i)=>{
    obj[i]=ele;
})
console.log('obj', obj)
Amit
  • 1
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};