5

Is there a way to destructure an object having a hyphen in the property names. I get a SyntexError while doing so (which is reasonable because JS doesn't allow variable name with a hyphen).

let human= {
    "first-name":"John",
    "last-name":"Doe",
    age:150
}

let {age}= human;
// let {"first-name"}= human;//error
// let {first-name}= human;//error

console.log(age)
dasfdsa
  • 7,102
  • 8
  • 51
  • 93

2 Answers2

5

You can alias the property name using the colon syntax.

let human = {
  "first-name": "John",
  "last-name": "Doe",
  age: 150
};

let { age, "first-name": firstName } = human;
console.log(age, firstName);
AKX
  • 152,115
  • 15
  • 115
  • 172
  • I was 98.3% sure that I won't get any answer (or the exact answer I am looking for) but StackOverflow never fails me. – dasfdsa Jul 16 '18 at 08:13
1

The reason behind the code not working for you is because first-name is not a valid variable name in Javascript as it considers that as a minus operator rather than hyphen during console.log(first-name). So, the fix could be to rename the object property to first_name and use it elsewhere.

let human= {
    "first-name":"John",
    "last-name":"Doe",
    age:150
}

let {age}= human;
let {'first-name':first_name}= human;

console.log(first_name)
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62