0

i am trying to destructure an array and return an object. but the key is not working inside the object. but outside of the object destructuring happening smoothly.

let [key, value] = ["b", 2];
    
let object = { key: value };

console.log(object); // {key: 2}

console.log(key, value)// b, 2
Hasan
  • 15
  • 4

1 Answers1

0

Bracket notation!

To use a variable as a key in objects...

Because when creating an object, the parser interprets the string in front of : as a key.
The string after the : for sure has to be a variable if it isn't wrapped with quotes to specify a string.
So for the key, it does not know you want to use the variable named like that string.
How to tell it is the brackets use.

let [key, value] = ["b", 2];
    
let object = { [key]: value };  // Brackets around the key variable

console.log(object); // {"b": 2}  As expected...

console.log(key, value)// b, 2
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64